【问题标题】:Watch promise (resource) changes in Angular 1.2.0+观察 Angular 1.2.0+ 中的承诺(资源)变化
【发布时间】:2013-12-08 03:08:18
【问题描述】:

我正在使用 $resource 在我的控制器中加载项目数组:

$scope.items = api.items.query();

$scope.items 现在是承诺。解析后,它包含项目数组。比我有一些方法,操纵项目,例如:

// template
<div ng-repeat="item in items">
    <a href="" ng-click="doSomething(item)">Do it!</a>
</div>

// controller:
$scope.doSomething = function(item) {
    item.$doSomething(); // the items 
};

我想在这里查看$scope.items 的变化,因此一旦有任何项目发生变化,它就会得到通知。我试过这个:

$scope.$watch($scope.items, function() {
    console.log('changed');
});

但这不起作用 - 在 doSomething 更改对象后不会触发它。第三个objectEquality 参数都没有帮助。我也试过$watchCollection,但没有运气。

我发现这在很短的时间内有效 - 自 Angular 1.2.rc2 引入了承诺解包 (https://github.com/angular/angular.js/issues/3503),但在 1.2.0 (https://github.com/angular/angular.js/issues/4158) 中已将其删除。

那么现在(当前稳定版是 Angular 1.2.4)有什么办法吗?

谢谢!

P.S.:这个问题也讨论过:AngularJS - binding/watching a function which returns a promise,但这不适用于 1.2.0+。

【问题讨论】:

  • 也许是因为这个? github.com/angular/angular.js/commit/…
  • 我知道,但是:“此功能已被弃用,如果绝对需要,可以在过渡期间重新启用” - 我不想依赖已弃用的功能......跨度>
  • 我刚刚遇到了同样的问题。你可以试试 $scope.$watch($scope.items.$resolved, function() {});
  • 您可以迭代项目并为每个项目添加手表。

标签: angularjs promise


【解决方案1】:

不要将 Promise 分配给 $scope.items,等到 Promise 解决后再将结果分配给 $scope.items。

api.items.query().then(function(itemsQueryResults){
  $scope.items = itemsQueryResults;
});

当 items 属性更新时,Angular 会像往常一样运行一个摘要循环,并且你的 ng-repeat 会填充。

【讨论】:

    【解决方案2】:

    在 Angular 1.4.6 中,我可以通过向 $watch 添加第三个参数来解决这个问题。请注意,我还必须通过字符串名称引用范围属性:

    $scope.$watch('items', function() {
        console.log('changed');
    }, true);
    

    【讨论】:

      猜你喜欢
      • 2015-12-06
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-29
      相关资源
      最近更新 更多