Angular $watch 不适用于数组和数据集合

Angular $watch is not working for arrays and data collections

我需要观察对象列表中的变化,并对变化执行一些操作,但是,Angular $watch 仅触发一次,即首次创建列表且初始对象是推入其中:

$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'});

解决方法是用$watchCollection代替$watch方法:

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

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

请注意,$watchCollection 仅监视 objects/arrays 中的 1 层深度。这对你来说似乎没问题。

要观看具有多个深度级别的更复杂的对象,需要将 $watch 与 "true" 作为第二个属性一起使用。

Check out this for a detailed explanation of $watch vs $watchCollection