24

Is there a way in AngularJS to combine this into the one $watch or do I still need a $watch for each thing I watch?

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

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

2 Answers2

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.

Denison Luz
  • 3,575
  • 23
  • 25
1

If you use angular 1.1.4, you can use $watchCollection, here is the code snippet from the sample code in the documentation.

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

$scope.$watchCollection('names', function(newNames, oldNames) {
  $scope.dataCount = newNames.length;
});
zs2020
  • 53,766
  • 29
  • 154
  • 219
  • -1: This is not what the OP asked for. Your snippet watches the '$scope.names' for changes. Please review the question carefully. He wanted to "pack up" multiple similar watches into one watch expression. dluz's last fragment (watching a list of scope variables) is the closest thing, because it's one expression that would 'watch' two scope variables. – quetzalcoatl Aug 28 '14 at 11:26