24

AngularJS 中有没有一种方法可以将它组合到一个 $watch 中,或者我是否仍然需要一个 $watch 来观看我观看的每一件事?

    $scope.$watch('option.selectedContentType', function () {
        $scope.getData();
    });

    $scope.$watch('option.selectedContentStatus', function () {
        $scope.getData();
    });
4

2 回答 2

44

You can find below some variations on how to use $watchCollection

http://jsbin.com/IYofiPi/4 - working example here.

Check your console.log to see the event being fired.

Watching items of an Array

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

Watching properties of an Object

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

Watching a list of scopes variables ($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]);
});

Starting from AngularJS 1.3 there's a new method called $watchGroup for observing a set of expressions.

于 2013-10-14T09:07:07.817 回答
1

如果您使用 angular 1.1.4,则可以使用$watchCollection,这是文档中示例代码的代码片段。

$scope.names = ['igor', 'matias', 'misko', 'james'];

$scope.$watchCollection('names', function(newNames, oldNames) {
  $scope.dataCount = newNames.length;
});
于 2013-07-26T04:37:00.877 回答