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();
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With