在我的作用域中有一个对象数组,我想观察每个对象的所有值。
这是我的代码:
function TodoCtrl($scope) {
$scope.columns = [
{ field:'title', displayName: 'TITLE'},
{ field: 'content', displayName: 'CONTENT' }
];
$scope.$watch('columns', function(newVal) {
alert('columns changed');
});
}
但是当我修改值时,例如我将TITLE更改为TITLE2,警报('列已更改')从未弹出。
如何深度观看数组内的对象?
有一个现场演示:http://jsfiddle.net/SYx9b/
$watchCollection完成了您想要做的事情。下面是一个从angularjs网站http://docs.angularjs.org/api/ng/type/$rootScope.Scope复制的例子
虽然很方便,但性能也需要考虑在内,尤其是当你观看大量收藏时。
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
下面是观察作用域变量的3种方法的比较和示例:
$watch()由以下方式触发:
$scope.myArray = [];
$scope.myArray = null;
$scope.myArray = someOtherArray;
$watchCollection()由以上所有AND触发:
$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value
美元的手表(…, true)由以上所有和触发:
$scope.myArray[0].someProperty = "someValue";
还有一件事……
$watch()是唯一一个在数组被另一个数组替换时触发的数组,即使另一个数组具有完全相同的内容。
例如,$watch()会触发而$watchCollection()不会:
$scope.myArray = ["Apples", "Bananas", "Orange" ];
var newArray = [];
newArray.push("Apples");
newArray.push("Bananas");
newArray.push("Orange");
$scope.myArray = newArray;
下面是一个JSFiddle示例的链接,该示例使用所有不同的手表组合,并输出日志消息来指示哪些“手表”被触发:
http://jsfiddle.net/luisperezphd/2zj9k872/
$watchCollection完成了您想要做的事情。下面是一个从angularjs网站http://docs.angularjs.org/api/ng/type/$rootScope.Scope复制的例子
虽然很方便,但性能也需要考虑在内,尤其是当你观看大量收藏时。
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
你可以设置$watch的第3个参数为true:
$scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);
见https://docs.angularjs.org/api/ng/type/ rootScope.Scope #美元的手表
从Angular 1.1开始。x你也可以使用$watchCollection来观看浅表(只是“第一层”)的集合。
$scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });
见https://docs.angularjs.org/api/ng/type/ rootScope.Scope # watchCollection美元