Jitesh Jitesh - 1 month ago 10
AngularJS Question

How to use $watchgroup or $watchCollection on 2 variable out of which one is array?

If we have 2 variable then we can use $watchCollection or $watchgroup as shown below.

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


How can we use $watchCollection if

$scope.myPlanet = 'Earth';
$scope.otherPlanet = ['Venus','Jupiter','Mars'];


and how to access the each variable value.

Answer

You can still use the same,

 $scope.$watchGroup(['myPlanet', 'otherPlanet'], function(newVals, oldVals, scope) {
    $log.log(newVals, oldVals, scope);
});

DEMO