3

我正在使用 PHP 将数据获取到我的工厂,这在控制器内的成功回调函数中正确显示。但是,即使在将返回的数据分配给 $scope.customers 之后,如果我在回调之后执行 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]);
4

2 回答 2

2

$http 函数异步发生。因此,在 之后调用 console.logcustomersFactory.getAllData将始终为空。

console.log($scope.customers); // Object with correct data

实际上发生在之后

console.log($scope.customers); // empty []

您可以相信成功回调设置$scope.customers正确,您只需要您的站点了解它稍后会发生。如果您需要在视图加载之前填充 scope.customers,请考虑在控制器上使用解析。

于 2014-07-30T17:52:04.047 回答
0

不是吗

console.log($scope.customers); // empty []

之前执行

console.log($scope.customers); // Object with correct data

?

第二个在 success() 回调中,因此它的执行时间可能比第一个晚得多。

于 2014-07-30T17:50:02.793 回答