Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

This is not an AngularJS feature; it is part of the HTML5 specification. Compliant browsers will consider this field
invalid if it does not contain a properly formatted e-mail address. I will touch on this point again in the upcoming
validation section.
The Marketing team has asked us to include some research questions in our registration form. It wants to
know among which set of communication channels the user has found our company. So far, we have created the
appropriate form element, shown again in the code snippet that follows. However, we currently present just one
option: the prompt for the user.



This select element needs some AngularJS work, because the select element itself is only half the story.
We have to turn to the controller, shown in Listing 6-10, whereby we can create some data for the list of options.


Listing 6-10. The Controller Code Driving the select Element


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


$scope.person = {};


$scope.person.channels = [
{ value: "television", label: "Television" },
{ value: "radio", label: "Radio" },
{ value: "social-media", label: "Social Media"},
{ value: "other", label: "Other"}
];


});


The controller, through the scope object, is making the person object available to our view template. More
specifically, because our select element needs this data, it adds an array of objects to the model property we use
on the select element’s ngModel directive: person.channels. Another step is required, because we want the select
element to be populated with a set of option elements, based on the model property we just added to the scope
above. For this step, we use the ngOptions directive. Listing 6-11 shows the revised select element.


Listing 6-11. Using the ngOptions Directive to Generate Options


<select name="channels" ng-model="person.channels"
ng-options="obj.value as obj.label for obj in person.channels">
option value="">Where did you hear about us?



The ngOptions directive expects a comprehension expression. This expression can seem a little intimidating when
you first encounter it, but we can break it down. It is essentially a query that we use to tell AngularJS how to map our
model property, the person.channels array, in this case, onto a set of HTML options. This array contains a set of
objects, and AngularJS would like to know which properties of this set should become the option element’s value and
which should become the content visible to our end user. Here is the expression again:


obj.value as obj.label for obj in person.channels

Free download pdf