本文介绍了观看Angular 1.2.0+中的Promise(资源)更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using $resource for loading array of items in my controller:

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

现在可以保证$scope.items.解决后,它包含项目数组.比我有一些操作项目的方法,例如:

The $scope.items is now promise. Once it is resolved, it contains array of items. Than I have some methods, manipulating the items, for example:

// 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中的更改,因此一旦任何项目更改,它就会得到通知.我试过了:

Here I would like to watch changes in $scope.items, so it gets notified once any of the item changes . I tried this:

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

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

but this doesn't work - it is not triggered after the doSomething changes the object. Neither helps the third objectEquality parameter. I also tried $watchCollection, but with no luck.

我发现这工作了很短的时间-自Angular 1.2.rc2以来,引入了可拆封的承诺( https://github.com/angular/angular.js/issues/3503 ),但在1.2.0中已将其删除( https://github.com/angular/angular.js/issues/4158 ).

I found this worked for a short period of time - since Angular 1.2.rc2 the promises unwraping was introduced (https://github.com/angular/angular.js/issues/3503), but it was removed in 1.2.0 (https://github.com/angular/angular.js/issues/4158).

那么现在有什么办法(当前稳定为Angular 1.2.4)怎么做吗?

So is there now (current stable is Angular 1.2.4) any way how to do this?

谢谢!

PS:在以下问题中也对此进行了讨论: AngularJS -绑定/监视返回诺言的函数,但这不适用于1.2.0 +.

P.S.: This was also discussed in this question: AngularJS - binding/watching a function which returns a promise, but this is not applicable for 1.2.0+.

推荐答案

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

In Angular 1.4.6, I was able to solve this by adding a third parameter to $watch. Note that I also had to reference the scope property by string name:

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

这篇关于观看Angular 1.2.0+中的Promise(资源)更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 01:48