javascript - AngularJS : $scope. $监视一个对象并仅返回其更改的属性

标签 javascript angularjs

我正在做一些简单的范围观察,例如:

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

其中 myObject 是一个具有多个属性的普通对象。我只想返回已更改的属性,即,如果有一个属性发生更改,例如 myObject.changedProperty,我只想返回该属性。

但是我想监视整个对象(因此,我不必为每个属性设置不同的监视)。如何才能做到这一点?

谢谢!

最佳答案

$watchCollection 可以满足您的需求。 ($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). 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. The listener is called whenever anything within the obj has changed. Examples include adding, removing, and moving items belonging to an object or array.

关于javascript - AngularJS : $scope. $监视一个对象并仅返回其更改的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30205873/

相关文章:

javascript - 如何在 IE11 中添加未定义或引用的属性

javascript - 是否可以更改 ngx-datatable-column 名称?

javascript - ExpressJS res.render 不适用于 angularjs

javascript - 为单个输入字段设置 ng-model 和 ng-value

javascript - Angular 指令更新父 Controller 对象

javascript - 带有动画/过渡的垂直切换的圆形菜单

javascript - 在 React 中重置表单输入值

javascript - 替换每个 HTML 控件的内容 javascript jquery

Javascript JSON 解析后不起作用

javascript - Angular js中的日期表列排序问题