Is there a way to subscribe to events on multiple objects using $watch
E.g.
$scope.$watch('item1, item2', function () { });
Is there a way to subscribe to events on multiple objects using $watch
E.g.
$scope.$watch('item1, item2', function () { });
Beginning with AngularJS 1.1.4 you can use
$watchCollection
:Plunker example here
Documentation here
Why not simply wrap it in a
forEach
?It's about the same overhead as providing a function for the combined value, without actually having to worry about the value composition.
Here's a solution very similar to your original pseudo-code that actually works:
EDIT: Okay, I think this is even better:
Basically we're skipping the json step, which seemed dumb to begin with, but it wasn't working without it. They key is the often omitted 3rd parameter which turns on object equality as opposed to reference equality. Then the comparisons between our created array objects actually work right.
$watch first parameter can be angular expression or function. See documentation on $scope.$watch. It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc.
A slightly safer solution to combine values might be to use the following as your
$watch
function:or
Angular introduced
$watchGroup
in version 1.3 using which we can watch multiple variables, with a single$watchGroup
block$watchGroup
takes array as first parameter in which we can include all of our variables to watch.