How to $watch for changes to a list?

angularjs, javascript

Solution

You are right, angular checks for reference by default, for perfomance reasons. The usage of reference vs equality depends on the value of the $watch function's third argument, as you can see in the docs. Just set it to true (it is false by default) and your fiddle will work - here it is, working.

the change:

$scope.$watch('names', function() {
        $scope.timesChanged++;
    }, true);

EDIT - Performance implications:

Comparing two arrays/objects can obviously be very inefficient (hence the check by reference angular makes by default), depending on the size and complexity of your variables. There is an alternate method - watching the length of the array. This has obvious limitations - changing one element no longer triggers the $watch function - but can be immensely faster. Here is an updated fiddle!

Problem

fiddle I have a list, and I'd like to be notified whenever it changes. A simple `$watch` expression isn't working, which I'm guessing is because angular is checking for referential equality, not structural equality. ``` <html ng-app> <head> </head> <body ng-controller="Root"> <h1>Base Angular Fiddle</h1> Times changed: {{timesChanged}} <ul> <li ng-repeat="name in names">{{name}}</li> <li><button ng-click="names.push('another name')">Add</button></li> </ul> </body> </html> ​ ​function Root($scope) { $scope.timesChanged = 0; $scope.names = ['foo', 'bar', 'baz']; $scope.$watch('names', function() { $scope.timesChanged++; }); }​ ``` What I'm hoping will happen is that the callback for `'names'` is called each time that I call `names.push()`. Is there a workaround that's recommended for this? Or am I just not using `$watch` correctly?

Original source