Javascript 观察多个 $scope 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11952579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:47:57  来源:igfitidea点击:

Watch multiple $scope attributes

javascriptangularjseventsangularjs-watch

提问by Greg

Is there a way to subscribe to events on multiple objects using $watch

有没有办法订阅多个对象上的事件使用 $watch

E.g.

例如

$scope.$watch('item1, item2', function () { });

回答by Paolo Moretti

Starting from AngularJS 1.3 there's a new method called $watchGroupfor observing a set of expressions.

从 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 
});

回答by R?zvan Flavius Panda

Beginning with AngularJS 1.1.4 you can use $watchCollection:

从 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 example here

Plunker 示例在这里

Documentation here

文档在这里

回答by Andrew Joslin

$watchfirst parameter can also be a function.

$watch第一个参数也可以是一个函数。

$scope.$watch(function watchBothItems() {
  return itemsCombinedValue();
}, function whenItemsChange() {
  //stuff
});

If your two combined values are simple, the first parameter is just an angular expression normally. For example, firstName and lastName:

如果您的两个组合值很简单,则第一个参数通常只是一个角度表达式。例如,名字和姓氏:

$scope.$watch('firstName + lastName', function() {
  //stuff
});

回答by Karen Zilles

Here's a solution very similar to your original pseudo-code that actually works:

这是一个与实际工作的原始伪代码非常相似的解决方案:

$scope.$watch('[item1, item2] | json', function () { });

EDIT:Okay, I think this is even better:

编辑:好的,我认为这更好:

$scope.$watch('[item1, item2]', function () { }, true);

Basically we're skipping the json step, which seemed dumb to begin with, but it wasn't working without it. They key is the often omitted 3rd parameter which turns on object equality as opposed to reference equality. Then the comparisons between our created array objects actually work right.

基本上我们跳过了 json 步骤,这在开始时似乎很愚蠢,但没有它就无法工作。他们的关键是经常被省略的第三个参数,它打开对象相等而不是引用相等。然后我们创建的数组对象之间的比较实际上是正确的。

回答by Yang Zhang

You can use functions in $watchGroup to select fields of an object in scope.

您可以使用 $watchGroup 中的函数来选择范围内对象的字段。

        $scope.$watchGroup(
        [function () { return _this.$scope.ViewModel.Monitor1Scale; },   
         function () { return _this.$scope.ViewModel.Monitor2Scale; }],  
         function (newVal, oldVal, scope) 
         {
             if (newVal != oldVal) {
                 _this.updateMonitorScales();
             }
         });

回答by Erik Aigner

Why not simply wrap it in a forEach?

为什么不简单地将它包装在 a 中forEach

angular.forEach(['a', 'b', 'c'], function (key) {
  scope.$watch(key, function (v) {
    changed();
  });
});

It's about the same overhead as providing a function for the combined value, without actually having to worry about the value composition.

它与为组合值提供函数的开销大致相同,而实际上不必担心值组合

回答by guyk

A slightly safer solution to combine values might be to use the following as your $watchfunction:

组合值的稍微更安全的解决方案可能是使用以下作为您的$watch函数:

function() { return angular.toJson([item1, item2]) }

or

或者

$scope.$watch(
  function() {
    return angular.toJson([item1, item2]);
  },
  function() {
    // Stuff to do after either value changes
  });

回答by Artem Andreev

$watch first parameter can be angular expressionor function. See documentation on $scope.$watch. It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc.

$watch 第一个参数可以是角度表达式或函数。请参阅有关$scope.$watch 的文档。它包含许多关于 $watch 方法如何工作的有用信息:何时调用 watchExpression,角度如何比较结果等。

回答by wacamo

how about:

怎么样:

scope.$watch(function() { 
   return { 
      a: thing-one, 
      b: thing-two, 
      c: red-fish, 
      d: blue-fish 
   }; 
}, listener...);

回答by Akash Shinde

$scope.$watch('age + name', function () {
  //called when name or age changed
});

Here function will get called when both age and name value get changed.

当年龄和名称值都改变时,这里的函数将被调用。