是否有一种方法可以使用$watch订阅多个对象上的事件
E.g.
$scope.$watch('item1, item2', function () { });
是否有一种方法可以使用$watch订阅多个对象上的事件
E.g.
$scope.$watch('item1, item2', function () { });
当前回答
为什么不简单地把它包在forEach里呢?
angular.forEach(['a', 'b', 'c'], function (key) {
scope.$watch(key, function (v) {
changed();
});
});
这与为组合值提供函数的开销大致相同,实际上不必担心值的组合。
其他回答
为什么不简单地把它包在forEach里呢?
angular.forEach(['a', 'b', 'c'], function (key) {
scope.$watch(key, function (v) {
changed();
});
});
这与为组合值提供函数的开销大致相同,实际上不必担心值的组合。
从AngularJS 1.3开始,有了一个名为$watchGroup的新方法,用于观察一组表达式。
$scope.foo = 'foo';
$scope.bar = 'bar';
$scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
// newValues array contains the current values of the watch expressions
// with the indexes matching those of the watchExpression array
// i.e.
// newValues[0] -> $scope.foo
// and
// newValues[1] -> $scope.bar
});
从AngularJS 1.1.4开始,你可以使用$watchCollection:
$scope.$watchCollection('[item1, item2]', function(newValues, oldValues){
// do stuff here
// newValues and oldValues contain the new and respectively old value
// of the observed collection array
});
这里是Plunker的例子
文件在这里
如何:
scope.$watch(function() {
return {
a: thing-one,
b: thing-two,
c: red-fish,
d: blue-fish
};
}, listener...);
您可以使用$watchGroup中的函数来选择范围内对象的字段。
$scope.$watchGroup(
[function () { return _this.$scope.ViewModel.Monitor1Scale; },
function () { return _this.$scope.ViewModel.Monitor2Scale; }],
function (newVal, oldVal, scope)
{
if (newVal != oldVal) {
_this.updateMonitorScales();
}
});