I want to watch for changes in a dictionary, but for some reason watch callback is not called.
Here is a controller that I use:
function MyController($scope) {
$scope.form = {
name: 'my name',
surname: 'surname'
}
$scope.$watch('form', function(newVal, oldVal){
console.log('changed');
});
}
Here is fiddle.
I expect $watch callback to be fired each time name or surname is changed, but it doesn't happen.
What is the correct way to do it?
Try this:
Little performance tip if somebody has a datastore kind of service with key -> value pairs:
If you have a service called dataStore, you can update a timestamp whenever your big data object changes. This way instead of deep watching the whole object, you are only watching a timestamp for change.
And in a directive you are only watching the timestamp to change
Call
$watch
withtrue
as the third argument:By default when comparing two complex objects in JavaScript, they will be checked for "reference" equality, which asks if the two objects refer to the same thing, rather than "value" equality, which checks if the values of all the properties of those objects are equal.
Per the Angular documentation, the third parameter is for
objectEquality
:For anyone that wants to watch for a change to an object within an array of objects, this seemed to work for me (as the other solutions on this page didn't):
The reason why your code doesn't work is because
$watch
by default does reference check. So in a nutshell it make sure that the object which is passed to it is new object. But in your case you are just modifying some property of form object not creating a new one. In order to make it work you can passtrue
as the third parameter.It will work but You can use $watchCollection which will be more efficient then $watch because
$watchCollection
will watch for shallow properties on form object. E.g.