AngularJs Update Cycle & the Ng-Model Directive

What actually goes on in AngularJs when you input a value?

Lets say we have an angular application with the following input bound to a scope variable

<input type="text" ng-model="" />

When angular "compiles", the input element of type text will be processed by angular's textInputType directive, which binds to the input's DOM change events.

When that input registers a change, here's what happens:

  1. angular reads the DOM element's value

  2. angular optionally trim's the value

  3. If the NgModelController.$viewValue does not equal the trimmed input value, then angular calls the controls.$setViewValue method, via the scope's $apply method.

  4. $setViewValue takes over here. In a nutshell, what $setViewValue does is set the input value to controller's $viewValue, run's the input value through the controller's list of $parsers, then applies the "parsed" value to the controller's $modelValue and then to the bound object.

  5. Once $setViewValue is complete, $apply then call's $digest on the scope. $digest recursively calls all the current scope and child scopes' $watch methods. Essentially, $digest tells the rest of your application to check for changes, thereby allowing it to respond dynamically to user input.

Tags: javascriptangular

comments powered by Disqus