Mastering Web Application

(Rick Simeone) #1
Chapter 11

After getting familiar with the scope $watch mechanism we should realize that our
simple-model directive would also benefit from model observing as a value in an
input field and should be updated in response to model changes:


.directive('simpleModel', function ($parse) {
return function (scope, element, attrs) {

var modelGetter = $parse(attrs.simpleModel);
var modelSetter = modelGetter.assign;

//Model -> DOM updates
scope.$watch(modelGetter, function(newVal, oldVal){
element.val(newVal);
});

//DOM -> Model updates
element.bind('input', function () {
modelSetter(scope, element.val());
});
};
})

With the recent changes to our simple directives we've set up watches in order
to observe model mutations. The code looks great and it is reasonable to expect
that it should work correctly. Unfortunately those examples still won't work in
a live application.


It turns out that we are missing one more fundamental piece of the whole puzzle:
when and how AngularJS monitors model changes. We need to understand under
which circumstances AngularJS will start evaluating all the watch expressions,
checking for model changes.


Scope.$apply – a key to the AngularJS world

When AngularJS was first released to the public there were many "conspiracy
theories" regarding its model-changes tracking algorithm. The most frequently
repeated one was based on suspicion that it uses some kind of polling mechanism.
Such a mechanism was supposedly kicking-in at certain intervals to check model
values for changes and re-rendering the DOM if changes were found. All of this
is false.


AngularJS does not use any kind of polling mechanism to periodically
check for model changes.
Free download pdf