Watch an entire object (deep clock) with AngularJS

This is the angular-resource variable / object scope that represents the form data:

  $scope.form = { name: 'bob', email: ' bob@bobs.com ' } 

I see how my variable name changes.

  $scope.$watch('form.name', function(newVal) { if(newVal) { alert(newVal) } }); 

How could one see if any of the names was changed - name, email address or any kind of scope.form?

My goal is to make my form โ€œkeepโ€ disabled or enabled, depending on whether the user has changed something on the form.

+6
source share
2 answers

There is a third parameter, $watch() , which will make it check the equality of the object (deep watch).

  $scope.$watch('form', function(newVal) { //watch the whole object if(newVal) { alert(newVal); } }, true); //pass "true" here. 

To complete my answer, both of these approaches lead to the same result in this case: Live demo here (click). but $watchCollection shallow and will not watch anything embedded in the changes.

  $scope.$watch('form', function(newForm, oldForm) { console.log(newForm.name); }, true); 

OR: (not deep hours)

  $scope.$watchCollection('form', function(newForm, oldForm) { console.log(newForm.name); }); 
+15
source

Since AngularJS 1.1.x, the preferred way to view multiple values โ€‹โ€‹in an array or object properties is $ watchCollection http://docs.angularjs.org/api/ng.$rootScope.Scope

 $scope.$watchCollection('form', function(newValues, oldValues) { console.log('*** Watch has been fired. ***'); console.log('New Names :', newValues);} ); 
+2
source

Source: https://habr.com/ru/post/959018/


All Articles