如何在 Angular 中 $watch 多个集合? [英] How to $watch more than one collection in Angular?

查看:20
本文介绍了如何在 Angular 中 $watch 多个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有两个数组,我想观察更改:

I have two arrays in my application I would like to observe changes:

$scope.a = [{id: 1, text: 'test a - 1'}, ...];
$scope.b = [{id: 1, text: 'test b - 1'}, ...];

function changed(){
  // notify application about changes in a or b
}

ab 已更改时,我必须调用 changed() 函数.

I have to call the changed() function when a or b have been changed.

$scope.$watchCollection('a', changed);
$scope.$watchCollection('b', changed);

如果我在 ab 以及 init 步骤中有更改,则 changed() 回调将被触发两次.我想将两个手表合二为一,如下所示:

The changed() callback will be triggered twice if I have changes in a and b as well as on init step. I would like to combine two watches in one, something like this:

$scope.$watchCollection('a, b', changed);

如何使用 Angular 执行此操作?

How can I do this with Angular?

推荐答案

有一种叫做 watchGroup 您可以将其用于此目的,但不幸的是,它几乎没用,因为它只能进行浅层观察.

There is something called watchGroup which you can use for this purpose, But unfortunately is is mostly useless as it does only shallow watch.

你可以使用 watcher 函数返回你的对象

You could use the watcher function to return your object

$scope.$watch(function(){ //Or even try this with watchCollection
     return ['a','b'].map(angular.bind($scope, $scope.$eval));
  }, function(newV){
      console.log(newV);
  },true);

您可以改为正如我在另一个答案中提到的那样,为方便起见,创建一个自定义观察器,然后执行类似的操作.

You could instead create a custom watcher for your convenience as i had mentioned in another answer and do something like this.

$scope.deepWatchGroup(['a','b'],function(newV){
  console.log(newV);
});

这篇关于如何在 Angular 中 $watch 多个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆