【问题标题】:ngRepeat not updating even though $resource hasngRepeat 不更新,即使 $resource 有
【发布时间】:2015-04-04 17:37:02
【问题描述】:

我有一个“添加朋友”对话框,当您添加用户时,它会返回状态历史记录并更新朋友列表。一切正常,除了列表没有显示新用户 - 即使console.logs 都显示了正确的数据:

[e, e, e, $promise: Promise, $resolved: true]

(3 es 是正确的,我之前有两个)。

$scope.add = function (user, goback) {
  if (goback)
    $ionicHistory.goBack();
  $ionicLoading.show();
  ApiService.friends.request(user._id, function (data, status, headers, cfg) {
    $scope.users = ApiService.users.friends(function (res, headers) {
      $ionicLoading.hide();
      console.log($scope.users);
    }); 
    console.log($scope.users);
  }); 
}

我尝试将 $scope.users = 包装在 $scope.$apply 中,或者在不同的地方调用它,但这只会(正确地)引发 $digest already in progress 错误(因为 $resource 会自动执行此操作)。

发生了什么,我该如何解决?


wtf 是怎么回事?我只是尝试这样做:

$scope.add = function (user, goback) {
  $scope.users = [];
}

(甚至将$scope.users = [] 包装在$apply 中)但什么也没发生! 但是 $scope.add 是从 ng-click 指令调用的 - 这应该可以工作!


发现实际错误!

我的添加好友视图,add 被调用,当然有它自己的 $scope。这很脏,但我最终使用$scope.$parent.users 而不是$scope.users 来保存数据。

【问题讨论】:

    标签: angularjs angularjs-scope angularjs-ng-repeat ngresource


    【解决方案1】:

    正如我在 OP 中所说,这是一个非常基本的范围错误,因为我忘记了我实际上是在两个操作之间切换 ui-router 视图,所以我的 $scope.users 实际上是两个不同的东西。

    将列表移动到$scope.$parent.users 暂时可以解决这个问题,尽管再次考虑一下,我可能应该将值移动到控制器中并使用MyController as ctrl 语法。

    【讨论】:

      【解决方案2】:

      我最近遇到了同样的问题。显然,$resource 使用的 $q 承诺仅在$digest 循环按设计(请参阅https://github.com/angular/angular.js/issues/2881)期间解决,这就是为什么在使用$scope.$apply 时会出现摘要进行中错误的原因.

      解决方法是将您的作业包装在 $timeout 中以强制执行另一个摘要循环,例如:

      $timeout(function() {
        $scope.users = ApiService.users.friends(); // Abbreviated
      });
      

      我不能 100% 确定您为什么要将 ApiService.users.friends() 的结果分配给 $scope.users,因为我猜该方法会返回一个承诺,但我可能会丢失更大的上下文。

      【讨论】:

      • users.friends 是 $resource 查询 (method: GET, isArray: true)。
      • 这仍然没有做任何事情......分配后的任何控制台调试输出仍然会打印三元素列表。
      猜你喜欢
      • 2016-07-05
      • 2015-08-11
      • 2013-03-12
      • 2017-06-29
      • 2014-11-21
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多