Reputation: 44386
My listener function depends on several values and I need to put $watch on each of them. I have thought of two ways:
scope.$watch(function() { return [calcOneValue(), calcTheOtherValue()]; },
function(a) { return theListener(a[0], a[1]); });
or
scope.$watch(calcOneValue,
function(a) { return theListener(a, calcTheOtherValue()); });
scope.$watch(calcTheOtherValue,
function(a) { return theListener(calcOneValue(), a); });
Are these the right ways to do this? Is there a better third option I am missing?
Should I genericize this, make a function that takes a scope, an array of value functions and one, multi-parameter listener function? Or does such a function already exist? Or does $watch do this already?
Upvotes: 0
Views: 336
Reputation: 49590
Angular has a built-in way to invoke the same function when any of specified expressions change - with $watchGroup
:
$scope.$watchGroup(["foo", "bar"], function(newValues, oldValues){
// do something when either $scope.foo or $scope.bar changes
});
Upvotes: 3
Reputation: 1690
You can deep watch an array by setting the third value of the call to true, and then put all your values in an array if you want.
scope.$watch(myArray,function() { ...},true);
Upvotes: 0