Beginning AngularJS

(WallPaper) #1

CHApTer 6 ■ WorkIng WITH ForMS


<select name="level" ng-model="person.levels"
ng-options="obj.label as obj.value for obj in person.channels">






<input ng-model="person.newsletterOptIn" type="checkbox" name="newsletterOptIn"
id="newsletterOptIn" value="newsletterOptIn"/>








The only change in the JavaScript code in Listing 6-15 is that the person object is constructed first and then
assigned to the $scope as the last step. The end result is the same, but this is much more readable.


Listing 6-15. The AngularJS Code


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


var person = {};
person.newsletterOptIn = false;
person.channels = [
{ value: "television", label: "Television" },
{ value: "radio", label: "Radio" },
{ value: "social-media", label: "Social Media"},
{ value: "other", label: "Other"}
];
person.register = function () {



}


});


Validating Forms


We usually want to validate at least some of the data that users enter into our forms. While it is true that validation
can and should be done on the server, and that server-side processes are usually capable of handling much more
complex validation rules, we still have to perform first-line-of-defense validation in the web browser. With JavaScript
validation, we can do a lot of the validation up front, before even considering sending it along to the server. This way,
we preserve bandwidth and reduce the load placed on our web servers. The fact that JavaScript validation provides
instant feedback is a big plus too.
Using AngularJS, it isn’t difficult or terribly time-consuming to implement JavaScript validation. The first step
has already been taken with our registration form: when we gave the form a name, we enabled access to AngularJS
validation features.

Free download pdf