Mastering Web Application

(Rick Simeone) #1

Writing Robust AngularJS Web Applications


The simple-bind directive presented here takes an expression (provided as
a DOM attribute), evaluates it against a $scope, and updates the text of a given
DOM element.


Synchronizing DOM and model

With both directives ready we could try to use them in HTML as shown in the
following code, and expect that new directives behave as the ng-model and
ng-bind equivalents:


<div ng-init='name = "World"'>
<input simple-model='name'>
<span simple-bind='name'></span>
</div>

Unfortunately running the last example won't yield expected results! While the
initial rendering will be correct, changes from the field won't trigger
updates in the element.


We must clearly be missing something and a quick review of the simple-bind
directive will help you realize that this directive covers only initial rendering of the
model. The directive doesn't observe model changes and won't react on those changes.
We can easily fix this by using the $watch method available on scopes' instances:


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

var modelGetter = $parse(attrs.simpleBind);
scope.$watch(modelGetter, function(newVal, oldVal){
element.text(modelGetter(scope));
});
}
});

The $watch method lets us monitor model mutations and execute functions in
response to model changes. This method has a signature that could be, in its
simplified form, described as follows:


scope.$watch(watchExpression, modelChangeCallback)

The watchExpression parameter can be either a function or AngularJS expression
(indicating model value to observe). The modelChangeCallback parameter is a
callback function that will get executed every time a value of the watchExpression
changes. The callback itself has access to both new and old values of the
watchExpression.

Free download pdf