Reputation: 3515
I need to watch on model changes in an object that sits in the controller. The object has multiple values:
$scope.myModel = {
first: 1,
second: 1,
third: 1
}
I want to catch changes to any of these values, but don't want to set up multiple watchers on each individual value, as it seems wasteful. Can I set up one $watch
that triggers when anything in the model has changed?
Upvotes: 2
Views: 470
Reputation: 21784
Pass true as a third argument to the $watch function, see the docs for scope :
$watch(watchExpression, [listener], [objectEquality]);
(...) ObjectEquality: Compare for object equality using angular.equals instead of comparing for reference equality
When objectEquality is false or not set, that means it will only check if it's the same object or not. Instead, setting it to true it will check if they are actually equal or not.
So the watch would look like:
$scope.$watch('variable', function(newValue, oldValue) {
// function code
}, true);
Upvotes: 3
Reputation: 17492
$scope.$watch("myModel",function(v){
console.log(v);
},true)
Should do it. The true
parameter is needed since you're watching child properties.
Upvotes: 2