Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : automatically detect change in model

Suppose I wanted to do something like automatically run some code (like saving data to a server) whenever a model's values change. Is the only way to do this by setting something like ng-change on each control that could possibly alter the model?

Ie, with views, things change right as the model is changed without having to explicitly hook anything up. Is there an analog to being able to run code that saves to a server? Something like

myModel.on('change', function() {   $.post("/my-url", ...); }); 

like you might see with something like backbone.

like image 598
alecbz Avatar asked Mar 15 '13 02:03

alecbz


1 Answers

In views with {{}} and/or ng-model, Angular is setting up $watch()es for you behind the scenes.

By default $watch compares by reference. If you set the third parameter to $watch to true, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:

$scope.$watch('myModel', function() { ... }, true); 

Update: Angular v1.2 added a new method for this, `$watchCollection():

$scope.$watchCollection('myModel', function() { ... }); 

Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.

like image 113
Mark Rajcok Avatar answered Sep 17 '22 12:09

Mark Rajcok