5

I'm interesting, how angular.js inside detect that model was changed, and what is general angular workflow for handling this changes. I mean, what really happened next on the page, after I change some part of my module.

silent_coder
  • 6,222
  • 14
  • 47
  • 91
  • 6
    Similar to [this question](http://stackoverflow.com/q/12463902/893780) (one of the answers there points to [this explanation](http://docs.angularjs.org/guide/concepts#runtime)). – robertklep Oct 05 '13 at 17:54

1 Answers1

0

This is my understanding. Correct me if I am wrong. This is two way information sharing :)

The data binding is not magic if you know how it is actually working behind.

In order for any variables to have the data binding features, it has to be registered using the $watch method.

$scope.$watch('aVarModel', function(newValue, oldValue) {
  //update the DOM with newValue
});

All these binded data through $watch will be checked whenever $scope.$digest is being called. Note that Angular do not check all values in scope but instead only those that registered using the $watch methods. If a model is not registered using watcher, it will not be checked. It compares the old values and the new values to check if any of it changes. If it changes, it will fires the listener function (the second parameter of watcher method).

You may asked you did not register any variable in scope using $watch or call $digest to check the changes but there is still data binding happens. Why?

AngularJS have bunch of built in directives that actually calls the $digest method behind it and watch the variable to make our job much easier. For example:

<div ng-app ng-init="qty=1;cost=2">
  <b>Invoice:</b>
  <div>
    Quantity: <input type="number" min="0" ng-model="qty">
  </div>
  <div>
    Costs: <input type="number" min="0" ng-model="cost">
  </div>
  <div>
     <b>Total:</b> {{qty * cost | currency}}
  </div>
</div>

The built in ng-model directives actually register watchers for qty and cost variables and call $scope.$digest everytime the value changes without we know it. You can create custom directives

Forgot to mention, every expression inside {{ }} is also automatically being watched in compile phase. So it will changes as the value of it changes anywhere in the app.

geckob
  • 7,680
  • 5
  • 30
  • 39