AngularJS:$http 成功回调中的范围问题 [英] AngularJS : Scope issue in $http success callback
问题描述
我正在使用 PHP 将数据导入我的工厂,这在控制器中的成功回调函数中正确显示.但是,即使在将返回的数据分配给 $scope.customers 之后,如果我在回调之后执行 console.log($scope.customers) 也不存在,并且我的视图的 [ng-repeat] 也没有拾取它.
I'm using PHP to get data into my factory, which shows correctly in the success callback function within the controller. However, even after assigning the returned data to $scope.customers, it's not there if I do a console.log($scope.customers) after the callbacks, and my view's [ng-repeat] isn't picking it up either.
如果我将返回的数据分配给 $scope 对象,为什么我的数据范围会被限制在成功回调内部?
Any idea why the scope of my data would be restricted to just inside the success callback if I'm assigning the returned data to my $scope object?
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 将始终为空.
$http functions happen asynchronously. Thus, calling console.log after the customersFactory.getAllData
will always be empty.
console.log($scope.customers);//数据正确的对象
实际上发生在
console.log($scope.customers);//空 []
您可以相信成功回调会正确设置 $scope.customers
,您只需要让您的网站了解它会在稍后发生.如果您需要在视图加载之前填充 scope.customers,请考虑在控制器上使用解析.
You can trust the success callback to set $scope.customers
correctly, you just need your site to understand that it will happen later. If you NEED scope.customers to be populated before the view loads, consider using a resolve on the controller.
这篇关于AngularJS:$http 成功回调中的范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!