CHApTer 6 ■ WorkIng WITH ForMS
It isn’t a particularly intuitive syntax, but we can make out the key components. In plain English, this would read
something like the following:
Use the value property on the option elements value attribute, and use the label property as the text
displayed within the option element. Oh, and by the way, I am referring to the objects contained
within the person.channels array.
■ Tip In AngularJS terminology, this kind of expression is known as a comprehension expression. It is used to create
a data source for the ngSelect directive from an object or an array. You can find out more in the online documentation
at https://docs.angularjs.org/api/ng/directive/select.
While we used the ngOptions directive to generate the option elements, we added the Where did you hear
about us? option manually. Of course, you could add an extra object to the person.channels array representing this
option too, but I prefer this approach, as it better reflects our ambitions about keeping things in the right place. This
option element is just an instruction to the user, and it exists only to serve as part of our user interface; it isn’t actually
part of our model.
Next up, we have the “Would you like to subscribe to our quarterly newsletter?” question. As this requires a yes
or no response, the checkbox element is well-suited to our needs. The only requirement that we have to address here
is that the Marketing team wants this check box to be unchecked by default. We automatically meet this requirement,
because check boxes are unchecked by default. However, we will set this explicitly through the binding we have set up
on the check box. Here is the check box again:
<input ng-model="person.newsletterOptIn" type="checkbox" name="newsletterOptIn"
id="newsletterOptIn" value="newsletterOptIn"/>
In our controller, we simply set the person.newsletterOptIn property to false. As this is used as a binding, the
check box, fully aware of the need to check and uncheck itself in response to true and false values, automatically
takes on the correct value. Had we wanted the check box to appear checked, we could have set this value to true
instead, which would have caused the check box to appear checked. Of course, it is not a good practice to put the onus
on the user to opt out, so we won’t do that. Listing 6-12 shows this in action.
Listing 6-12. The Controller Code Driving the Check Box
angular.module("myapp", [])
.controller("MyController", function ($scope) {
$scope.person = {};
$scope.person.newsletterOptIn = false;
$scope.person.channels = [
{ value: "television", label: "Television" },
{ value: "radio", label: "Radio" },
{ value: "social-media", label: "Social Media"},
{ value: "other", label: "Other"}
];
});