Beginning AngularJS

(WallPaper) #1
Chapter 8 ■ Organizing Views

Eager vs. Conservative Routes

Routes such as '/contact/:subject' are known as conservative routes. That’s really just a way of saying that the
route would match, say, '/contact/howareyou' but would not match 'contact/how/are/you', as the latter has far
too many URL segments. A conservative route is really quite strict about what it considers to be a match. To explain
how an eager route works, let’s start by considering a URL that contains segments that describe a product, more
specifically, a shirt that is available in various sizes, styles, and colors.


/product/123/medium/blue/loosefit
/product/698/large/green/snugfit


Knowing what we already know, this is not a problem for us; we can use a conservative route. Such a route would
look like this:


when('/product/:id/:size/:color/:fit', {
templateUrl: 'pages/product.html',
controller: 'productController'
});


Inside our controller, we can do just as we did earlier and use $routeParams to access each value.
$routeParams['color'] would give us the color, and $routeParams['size'] would give us the size, for example.
However, this is still a conservative route. To match, it needs a URL with all five segments. With an eager route, you
can do something like this:


when('/product/:id/:data*', {
templateUrl: 'pages/product.html',
controller: 'productController'
});


Note that the use of the asterisk that suffixes the data parameter essentially says “match any path that has at least
three segments, of which the first segment is product.” The second segment will be assigned to the route parameter id,
and the remaining segments will be assigned to the route parameter data.


■ Tip an eager route parameter is denoted by a colon, followed by a name, and then finally an asterisk. the key


difference between an eager route parameter and a conservative route parameter is that the latter will match one


segment, and the former will match as many segments as possible.


I personally haven’t had a need to use this kind of route parameter before, but they can be useful in certain
scenarios. For example, perhaps some shirts do not come with a slim-fit or loose-fit option, and perhaps some shirts
have even more options. An eager route is flexible in such cases, as fewer or more options are simply fewer or more
URL segments.


Route Configuration Options

We haven’t looked at everything there is to know about the Angular routing system, though we’ve certainly reviewed
enough to get you off to a good start. Before I finish this chapter, I’d like to leave you with a reference to some
additional configuration options, as shown in Table 8-3, if only to give you a sense of what else is available.

Free download pdf