Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 a 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?

1 Answer

0 votes
by (106k points)

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.

Call $watch with true as the third argument:

$scope.$watch('form', function(newVal, oldVal){ console.log('changed'); }, true);

Browse Categories

...