简体   繁体   English

AngularJS:$ scope。$ watch一个对象并仅返回其更改后的属性

[英]AngularJS : $scope.$watch an object & return only its changed property

I'm doing some simple scope watching like: 我正在做一些简单的示波器观察,例如:

$scope.$watch('myObject', function(newValue, oldValue) {
    if (newValue !== oldValue) {
       return newValue;
    }
}, true);

Where myObject is a normal object that has several properties. 其中myObject是具有多个属性的普通对象。 I would like to only return the property that changed, Ie, if there's a property which gets changed, like myObject.changedProperty , I would like to just return that. 我只想返回已更改的属性,即,如果有一个属性被更改,例如myObject.changedProperty ,我只想返回该属性。

Yet I want to watch the entire object (so, I don't have to set up different watches for each property). 但是我想监视整个对象(因此,我不必为每个属性设置不同的监视)。 How can this be done? 如何才能做到这一点?

Thank you! 谢谢!

$watchCollection does what you want. $ watchCollection可以满足您的需求。 ( $rootScope.Scope ) $ rootScope.Scope

$watchCollection(obj, listener);

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). Shallow监视对象的属性,并在任何属性更改时触发(对于数组,这意味着监视数组项;对于对象映射,这意味着监视属性)。 If a change is detected, the listener callback is fired. 如果检测到更改,则会触发侦听器回调。

The obj collection is observed via standard $watch operation and is examined on every call to $digest() to see if any items have been added, removed, or moved. obj集合通过标准$ watch操作进行观察,并在每次调用$ digest()时进行检查,以查看是否已添加,删除或移动了任何项目。 The listener is called whenever anything within the obj has changed. 只要obj中的任何内容发生更改,都将调用侦听器。 Examples include adding, removing, and moving items belonging to an object or array. 示例包括添加,删除和移动属于对象或数组的项目。

Thanks for the help everyone. 感谢大家的帮助。 I ended up doing something like this: 我最终做了这样的事情:

$scope.$watch('myObj', function(newValue, oldValue) {
    for (var prop in myObj) {
        if(newValue[prop] !== oldValue[prop]) {
           return newValue[prop];
        }
    }
}, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM