Beginning AngularJS

(WallPaper) #1
CHApTer 6 ■ WorkIng WITH ForMS

This approach is not quite as easy as adding the checked attribute to the HTML code, but it’s not too much extra
effort. I chose this approach because it better showcases bindings in action. However, it also has benefits in other
scenarios, such as when you have to populate forms with existing data (as with forms that users can come back and
update at a later time).
The last form element is the submit button. The only thing we have done so far is to change its value to
“register”, as opposed to leaving it with the default “Submit” value. The Marketing team has yet to tell us how we
should handle this data with regard to what should happen when a user registers, but I suspect it will have filled us
in on this just in time for the next chapter. For now, though, we can attach a submit handler to our form, so that it is
ready to handle this pending requirement. Here is the revised form element:



By using the ngSubmit directive, we have told the form to use a method on our person object (the register()
method) when the user submits the form. The revised controller code is shown in Listing 6-13.


Listing 6-13. Adding the submit Handler


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"}
];


$scope.person.register = function () {



}


});


We are closer to fulfilling the requirements, but there is still work to be done. Before we move on to the topic of
validation, it’s time for a checkpoint. Listing 6-14 shows the HTML code, and Listing 6-15 shows the slightly refactored
JavaScript code.


Listing 6-14. The Form Code












Free download pdf