Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch an object

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?

like image 351
Vladimir Sidorenko Avatar asked Oct 18 '13 17:10

Vladimir Sidorenko


People also ask

How do I watch nested objects in Vue?

We can watch for nested properties with watchers by adding methods to the watch property object with a property path. Also, we can set deep to true to watch for deeply nested properties.

What is watcher in VUE JS?

A Watcher in Vue. js is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic way to observe and react to data changes in the Vue instance. Watchers are the most useful when used to perform asynchronous operations.

Can you watch a computed property Vue?

You can even watch other computed props, as well as reactive data in data() ! Computed properties are required to be pure functions. This means that they return a new value, but aren't allowed to change anything, and they must be synchronous.

How do you watch props in Vue?

To watch for prop changes with the Vue. js Composition API, we can call the watch function. watch( () => props.


1 Answers

Call $watch with true as the third argument:

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

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:

When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications.

like image 120
rossipedia Avatar answered Sep 18 '22 19:09

rossipedia