Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I combine watching of multiple fields into one watch with AngularJS? [duplicate]

Tags:

angularjs

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

1 Answers

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.

like image 178
Denison Luz Avatar answered Sep 14 '25 21:09

Denison Luz