Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

Here is the associated controller code:

Listing 6-7. Implict Model Binding—Controller Code


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


$scope.showFirstName = function(){
alert("Name is: " + $scope.firstName);
}


});


Unlike in Listing 6-4 and Listing 6-5, the controller shown in Listing 6-7 does not create a model for our view
template to use. However, as you can see in Listing 6-6, we clearly refer to a model property called firstName in the
ngModel directive. Furthermore, we also show its value to the user when the Show first name button is pressed.
How and when is the firstName model property created?
AngularJS created this model property for us when it came across the ngModel directive on the text input
element. More accurately, it created it once it encountered a value to which it could bind. When the page first loads,
you can click the Show first name button, and you will get the result shown in Figure 6-2.


Figure 6-2. An empty text input—nothing to bind to


Perhaps, as you might expect, the value of firstName is displayed as undefined. Currently, there is no such model
property, so this makes perfect sense. Now let’s enter some text into the text input (see Figure 6-3).

Free download pdf