如何深入观察angularjs中的数组? [英] How to deep watch an array in angularjs?

查看:19
本文介绍了如何深入观察angularjs中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的作用域中有一个对象数组,我想查看每个对象的所有值.

There is an array of objects in my scope, I want to watch all the values of each object.

这是我的代码:

function TodoCtrl($scope) {
  $scope.columns = [
      { field:'title', displayName: 'TITLE'},
      { field: 'content', displayName: 'CONTENT' }
  ];
   $scope.$watch('columns', function(newVal) {
       alert('columns changed');
   });
}

但是当我修改值时,例如我将 TITLE 更改为 TITLE2alert('columns changed') 从未弹出.

But when I modify the values, e.g. I change TITLE to TITLE2, the alert('columns changed') never popped.

如何深入观察数组内的对象?

How to deep watch the objects inside an array?

有现场演示:http://jsfiddle.net/SYx9b/

推荐答案

您可以将$watch的第三个参数设置为true:

You can set the 3rd argument of $watch to true:

$scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);

参见 https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

从 Angular 1.1.x 开始,您还可以使用 $watchCollection 来观看浅表(只是第一级")集合.

Since Angular 1.1.x you can also use $watchCollection to watch shallow watch (just the "first level" of) the collection.

$scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });

参见 https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchCollection

这篇关于如何深入观察angularjs中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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