Chapter 11
Updating models in response to DOM events
AngularJS propagates changes from the DOM tree to the model through DOM event
listeners registered by different directives. The code in event-listeners mutate the
model by updating variables exposed on a $scope.
We can write a simplified equivalent of the ng-model directive (let's call it
simple-model) that would illustrate essential bits involved in updating the model:
angular.module('internals', [])
.directive('simpleModel', function ($parse) {
return function (scope, element, attrs) {
var modelGetter = $parse(attrs.simpleModel);
var modelSetter = modelGetter.assign;
element.bind('input', function(){
var value = element.val();
modelSetter(scope, value);
});
};
});
The key part of the simple-model directive consists of the input DOM event
handler that listens to changes in an input element and updates the model based
on the value entered by a user.
To set the actual model value we are using the $parse service. This service can be
put in action to both evaluate AngularJS expressions against a scope and set a model's
value on a scope. The $parse service, when called with an expression as its argument,
will return a getter function. The returned getter function will have the assign
property (a setter function) if the supplied AngularJS expression is assignable.
Propagating model changes to the DOM
We can use the $parse service to write a simplified version of the ng-bind directive
that can render model values as DOM text nodes:
.directive('simpleBind', function ($parse) {
return function (scope, element, attrs) {
var modelGetter = $parse(attrs.simpleBind);
element.text(modelGetter(scope));
}
});