0

我有时非常非常随机地无法使用 $http 调用中收到的数据。这样接收到的数据将绑定到接收它的变量,但不会传输到另一个变量。例如,下面的 {{avariable}} 显示在 HTML 页面中(它不再为 null 并显示来自服务器的数据)但 {{anumber}} 不会从 0 更改为新数据(即使我做了 $scope .anumber = $scope.avariable)。有时这个问题是通过在 $http 调用本身而不是稍后分配相等性来解决的,但是这一次它也不是那样工作的。我想这与摘要,评估周期有关吗?我不一定能很好地理解它们或它们在这种情况下是如何工作的。不过,我确实在必要时使用了 $timeout。

一切都在 Rails/后端工作 - 我通过直接转到浏览器中的 URL 进行检查。当然,如前所述,{{avariable}} 确实从 null 更改为服务器数据。

AngularJS 代码:

myangularmodule.controller('appcontroller', function($rootScope, $scope, $filter, $location, $state, $timeout, $http) {

$scope.avariable = null;

$scope.anumber = 0;


$scope.ihappenwhenthatbuttonispressed {

$timeout(function(){
 $http.get('/employees/getthisdata/' + value + '.json').success(function (data) {

        $scope.avariable = data.avariable;

    });
}, 5);

         $scope.anumber = $scope.avariable;



};


});

我的 HTML 页面:

<html>
<head>
 <%= stylesheet_link_tag "application" %>
 <%= javascript_include_tag "application" %>
</head>

 <body ng-app="myangularmodule">
  <div ng-controller="appcontroller">

    <button ng-click="ihappenwhenthatbuttonispressed(anumber)">
         Click me
   </button>

     {{avariable}}
     {{anumber}}

 </div>
 </body>
</html>
4

2 回答 2

0

这是因为 Javascript 中的 AJAX 调用是异步的。您正在调用 http 请求,然后立即设置$scope.anumber = $scope.avariable而不等待 http 响应。因此,当您第一次单击按钮时,您实际上是在设置$scope.anumber = null. 收到 http 响应后,$scope.avariable将其设置为您的data.variable,然后函数退出。

如果要同时更新两者,则需要以下内容:

$http.get('/employees/getthisdata/' + value + '.json').success(function (data) {
    $scope.avariable = data.avariable;
    updateANumber();
});
function updateANumber(){
    $scope.anumber = $scope.avariable;
}
于 2015-10-07T23:14:08.970 回答
0

你也可以这样做:

$http.get('/employees/getthisdata/' + value + '.json').success(function (data) {
    $scope.avariable = data.avariable;
    $scope.anumber = $scope.avariable;
});

不需要超时部分。

于 2015-10-07T23:18:54.803 回答