[医]AngularJS :$Http成功回调中的作用域问题
题
我正在使用PHP将数据获取到我的工厂,这在控制器内的成功回调函数中正确显示。但是,即使在将返回的数据分配给$scope之后。客户,如果我做一个控制台就不在那里。log($scope.客户)在回调之后,我的视图的[ng-repeat]也没有拿起它。
如果我将返回的数据分配给我的$scope对象,为什么我的数据范围将被限制在success回调内部?
var customersController = function($scope, customersFactory) {
$scope.customers = [];
customersFactory.getAllData()
.success(function(customers) {
$scope.customers = customers;
console.log($scope.customers); // Object with correct data
}); // No errors so only showing happy path
console.log($scope.customers); // empty []
};
customersModule.controller('customersController', ['$scope', 'customersFactory', customersController]);
解决方案
◦http函数异步发生。因此,调用控制台。日志后 customersFactory.getAllData
将永远是空的。
console.log($scope.customers); // Object with correct data
实际上是在之后发生的
console.log($scope.customers); // empty []
您可以信任要设置的成功回调 $scope.customers
正确的,你只需要你的网站了解它会在以后发生。如果你需要范围。要在视图加载之前填充客户,请考虑在控制器上使用解析。
其他提示
不是
console.log($scope.customers); // empty []
.
在
之前执行console.log($scope.customers); // Object with correct data
.
?
第二个是成功()回调,所以它可以比第一个更晚。
不隶属于 StackOverflow