[javascript] 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.

This question is related to javascript angularjs

The answer is


And if you need to style your form elements according to it's state (modified/not modified) dynamically or to test whether some values has actually changed, you can use the following module, developed by myself: https://github.com/betsol/angular-input-modified

It adds additional properties and methods to the form and it's child elements. With it, you can test whether some element contains new data or even test if entire form has new unsaved data.

You can setup the following watch: $scope.$watch('myForm.modified', handler) and your handler will be called if some form elements actually contains new data or if it reversed to initial state.

Also, you can use modified property of individual form elements to actually reduce amount of data sent to a server via AJAX call. There is no need to send unchanged data.

As a bonus, you can revert your form to initial state via call to form's reset() method.

You can find the module's demo here: http://plnkr.co/edit/g2MDXv81OOBuGo6ORvdt?p=preview

Cheers!