【问题标题】:AngularJS : Scope issue in $http success callbackAngularJS:$http成功回调中的范围问题
【发布时间】:2014-09-22 11:47:11
【问题描述】:

我正在使用 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]);

【问题讨论】:

  • 回调是在...之后调用的
  • 这是真的,当返回的数据在成功内分配给 $scope 时,我应该将我的问题更多地集中在我提到我的视图 [ng-repeat] 没有拾取数据的地方。

标签: javascript angularjs angularjs-scope angularjs-controller angularjs-factory


【解决方案1】:

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

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

实际上发生在

之后

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

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

【讨论】:

  • 我认为带有 ng-repeat 的视图与控制器绑定,所以当控制器更新时,视图也会更新。我愿意假设 success() 本身就很好,但是当 ng-repeat 也没有显示数据时,视图没有更新让我感到困惑。
  • 你是对的,数据“是”成功的,只是相信并坚持下去,这成为我研究/调试的基础。这导致我发现了我如何引用数据的问题。 $scope.customers = 客户.goodCustomers; // 视图没有可显示的内容,因为返回的客户数组有一个客户类型的子数组。不过,我很欣赏深入研究和尝试路由解析,以及了解 $scope.apply() - 显然两者都没有应用,但这是一次很好的学习体验。
【解决方案2】:

不是

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

执行前

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

?

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

【讨论】:

  • success() 稍后执行,正确。这就是我相信@Fourth 所指的。
猜你喜欢
  • 2015-04-19
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-16
  • 2013-12-22
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多