Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

■ Note AngularJS model binding happens inside a process called the digest loop. In simple terms, the digest loop is


triggered whenever a change is detected in the values that AngularJS is watching. I use the term near real time here,


because this process, despite how fast it is, is technically not in “real time.” There are advanced-use cases for which this


subtlety matters.


How do we set up a binding between a model property, such as firstName, and a text input? Well, it’s surprisingly
easy, thanks to the ngModel directive.



Here, we use the ngModel directive on the input to define a two-way binding. Because we specified firstName as
the value of the ngModel directive, we connected it to the model property of the same name. A very important aspect
of this process is the fact that it all happens against the current scope. In this particular (and common) scenario,
it would be the scope object used in your controller. When firstName was bound to the text input, it was actually
$scope.firstName that was bound. As discussed earlier in the book, the scope reference is implicit within AngularJS
expressions.
Let’s look at Listing 6-4 and see some model binding in action. Here is the controller code:


Listing 6-4. Setting Some Model Properties on the Scope


angular.module("myapp", [])
.controller("MyController", function ($scope) {


var person = {
firstName:"Jimmy",
age: 21,
address:{
street: '16 Somewhere Drive',
suburb: 'Port Kennedy',
state: 'Western Australia'
}
}


$scope.person = person;


});


Now let’s look at Listing 6-5, which shows a portion of HTML code that uses this controller and model.

Listing 6-5. ngModel in Action