观察多个$ scope属性

本文翻译自:Watch multiple $scope attributes

Is there a way to subscribe to events on multiple objects using $watch 有没有办法使用$watch订阅多个对象上的事件

Eg 例如

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

#1楼

参考:https://stackoom.com/question/o9PX/观察多个-scope属性


#2楼

$watch first parameter can also be a function. $watch first参数也可以是一个函数。

$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: 例如,firstName和lastName:

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

#3楼

$watch first parameter can be angular expression or function. $ watch第一个参数可以是角度表达式或函数。 See documentation on $scope.$watch . 请参阅$ scope的文档。$ watch It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc. 它包含许多关于$ watch方法如何工作的有用信息:调用watchExpression时,角度如何比较结果等。


#4楼

A slightly safer solution to combine values might be to use the following as your $watch function: 组合值的更安全的解决方案可能是使用以下作为$watch函数:

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

or 要么

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

#5楼

how about: 怎么样:

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

#6楼

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. 基本上我们正在跳过json步骤,这一步似乎开始时是愚蠢的,但没有它就无法工作。 They key is the often omitted 3rd parameter which turns on object equality as opposed to reference equality. 它们的关键是经常省略的第3个参数,它打开对象相等而不是引用相等。 Then the comparisons between our created array objects actually work right. 然后我们创建的数组对象之间的比较实际上是正确的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值