【发布时间】: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+。
【问题讨论】:
-
我知道,但是:“此功能已被弃用,如果绝对需要,可以在过渡期间重新启用” - 我不想依赖已弃用的功能......跨度>
-
我刚刚遇到了同样的问题。你可以试试 $scope.$watch($scope.items.$resolved, function() {});
-
您可以迭代项目并为每个项目添加手表。