Beginning AngularJS

(WallPaper) #1

Chapter 8 ■ Organizing Views


The second segment in this route acts as a reference to whatever value is actually supplied as the second segment
of a matching URL. Table 8-2 should shed some light on possible values for the subject route parameter, and it shows
a couple of non-starters.


How can we do something useful with this? The first step is to extract the value of the route parameter. What we
will use it for here is a simple comparison that will help us determine the text with which we want to pre-populate the
subject text field. This is shown in Listing 8-14, which is a revision of the contactController code.


Listing 8-14. The Revised contactController


app.controller('contactController', function ($scope, $routeParams) {


var subject = '';
if ($routeParams ['subject'] == "learn") {
subject = 'I want to learn more about your services';
} else if ($routeParams ['subject'] == "quote") {
subject = 'I would like to get a free quote';
}


$scope.subject = subject;
});


Extracting the value is easy, provided that we make the $routeParams service available to the controller, as we
do here. We then create the variable subject, initializing it to an empty string. The conditional logic revolves around
the value of the route parameter, and here you can see this value being retrieved via its name (also subject). Indexing
into the $routeParams service in this way tells us the value that was actually used in the URL. As to how it got into the
URL, let’s look at the changes I made to the about.html view template (see Listing 8-15).


Listing 8-15. Creating URLs That Contain Route Parameter Values



About Page


If you want to learn more about us please let us know.


If you want a free quote give us a call or inquire through
our contact form
.



Here you see the two links that will take us to the contact view template. Both /contact/learn and /contact/
quote are a match for /contact/:subject. Of course, the route parameter subject is given a different value for each:
learn for the former and quote for the latter. Listing 8-16 shows the new routes configuration.


Table 8-2. Possible Values for the subject Route Parameter


URL Match?


/contact/quote Yes. The route parameters value is quote.


/contact/learn Yes. The route parameters value is learn.


/contact/ Too few segments, no match


/contact/learn/more Too many segments, no match

Free download pdf