Beginning AngularJS

(WallPaper) #1

CHApTer 6 ■ WorkIng WITH ForMS


This time, the value of firstName is “Jimmy.” As AngularJS is working in real time, once the text was input, it was
able to create the binding. It’s good to be aware of this behavior. Nonetheless, the fact that it can result in values such
as undefined means that you should code defensively. This is demonstrated in Listing 6-8.


Listing 6-8. Coding Defensively


$scope.showFirstName = function(){
if(angular.isDefined($scope.firstName)){
alert("Name is: " + $scope.firstName);
}else{
alert("Name is empty, please enter a value");
}


}


In Listing 6-8, we first test to see if the model property exists, and we only display it if it does. This listing uses
the handy angular.isDefined method. In this version of the showFirstName function, the result of angular.
isDefined($scope.firstName) will be true, even if you were to backspace and remove all of the text from the First
name field. It will output an empty string as the value, although this is quite different from an undefined value.
AngularJS has previously found a value in this text input; consequently, the binding and associated variable has been
created and remains in play.


■ Tip angular.isDefined is just one of many handy utility methods that you can use. These methods can save you


time and offer a standard approach to certain tasks. I encourage you to look them up in the documentation, which you


can find here: https://docs.angularjs.org/api/ng.


With this knowledge of binding under our belts, let’s now move on to using it to create forms. More specifically,
we will create a small but, I hope, enlightening user registration form.


Figure 6-3. Text has been entered into the text input

Free download pdf