您可以在下面找到有关如何使用 $watchCollection 的一些变体
http://jsbin.com/IYofiPi/4 - working example here.
检查您的 console.log 以查看被触发的事件。
观察数组中的项目
$scope.cities = ['Salvador', 'London', 'Zurich', 'Rio de Janeiro']; //Array
$scope.$watchCollection('cities', function(newValues, oldValues) {
console.log('*** Watched has been fired. ***');
console.log('New Names :', newValues);
});
观察对象的属性
$scope.city = {
name: 'London',
country: 'England',
population: 8.174
}
$scope.$watchCollection('city', function(newValues, oldValues) {
console.log('*** Watched has been fired. ***');
console.log('New Names :', newValues);
});
查看范围变量列表($scope.firstPlanet、$scope.secondPlanet)
$scope.firstPlanet = 'Earth';
$scope.secondPlanet = 'Mars';
$scope.$watchCollection('[firstPlanet, secondPlanet]', function(newValues){
console.log('*** Watched has been fired. ***');
console.log('New Planets :', newValues[0], newValues[1]);
});
从 AngularJS 1.3 开始,有一个名为 $watchGroup 的新方法用于观察一组表达式。