Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deep watch an array in angularjs?

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

This is my code:

function TodoCtrl($scope) {   $scope.columns = [       { field:'title', displayName: 'TITLE'},       { field: 'content', displayName: 'CONTENT' }   ];    $scope.$watch('columns', function(newVal) {        alert('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?

There is a live demo: http://jsfiddle.net/SYx9b/

like image 444
Freewind Avatar asked Feb 05 '13 16:02

Freewind


2 Answers

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

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

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

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) { /*...*/ }); 

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

like image 97
Piran Avatar answered Oct 02 '22 08:10

Piran


There are performance consequences to deep-diving an object in your $watch. Sometimes (for example, when changes are only pushes and pops), you might want to $watch an easily calculated value, such as array.length.

like image 24
wizardwerdna Avatar answered Oct 02 '22 10:10

wizardwerdna