我有时非常非常随机地无法使用 $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>