AngularJS: $http成功回调的作用域问题

AngularJS : Scope issue in $http success callback

本文关键字:作用域 问题 回调 成功 http AngularJS      更新时间:2023-09-26

我使用PHP将数据输入工厂,这在控制器内的成功回调函数中正确显示。然而,即使将返回的数据赋值给$scope。如果我在回调之后执行console.log($scope.customers),它就不存在了,并且我的视图的[ng-repeat]也没有拾取它。

如果我将返回的数据分配给我的$scope对象,为什么我的数据范围将被限制在成功回调的内部?

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将始终为空。

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

?

第二个是在success()回调中,所以它可以比第一个执行得晚得多。