Search code examples
arraysangularjsonchangeangularjs-watch

Angular $watch is not working for arrays and data collections


I need to watch for changes in the list of objects, and perform some action on change, however, Angular $watch is triggered only once, when list was first created and initial object was pushed into it:

$scope.$watch('components', function(newComponents, oldComponents) {
  if (typeof $scope.components !== 'undefined')) {
    return;
  }
  // this alert show only on first change
  alert('change');
});

// only pushing first object triggers the $watch
$scope.components.push({ id: 1, name: 'first component'});
$scope.components.push({ id: 2, name: 'second component'});
$scope.components.push({ id: 3, name: 'third component'});

Solution

  • The solution is to use $watchCollection instead of $watch method:

    $scope.$watchCollection('components', function(newComponents, oldComponents) {
      if (typeof $scope.components !== 'undefined')) {
        return;
      }
      // now this alert will show for each new element added!
      alert('change');
    });
    

    Source: https://code.angularjs.org/1.3.15/docs/api/ng/type/$rootScope.Scope#$watchCollection