Beginning AngularJS

(WallPaper) #1

Chapter 8 ■ Organizing Views


app.controller('notFoundController', function ($scope) {
$scope.message = 'There seems to be a problem finding the page you wanted';
$scope.attemptedPath = $location.path();


You may have correctly surmised that the last controller complements our otherwise() route definition. Using
$location.path(), this controller does something slightly more interesting; it sets a value for $scope.attemptedPath,
so that we can display the invalid URL. This is the URL that could not be matched. Figure 8-3 shows how this looks.


If you load and view the index.html file at this stage, you will have a fully working, albeit minimal, web site. Take
some time to follow the links back and forth, observing the structure of the URLs and entering random URLs to see
the otherwise() method in action. Once you are ready, we will move on and build up your knowledge of the routing
system further.


Route Parameters

The URLs we have used to define our routes so far have been relatively simple but somewhat inflexible. This is
because the match against $location.path() has had to be exact. This is perfectly fine in many cases, but not when
we want to add parameters to our URLs. Examine the following three route definitions.


$routeProvider.when("/product/123", { templateUrl: "product.html" });
$routeProvider.when("/product/789", { templateUrl: "product.html" });
$routeProvider.when("/product/926", { templateUrl: "product.html" });


All of these use a fictitious product catalog view template, product.html, but each has a slightly different URL.
They each have a different series of numbers representing a product id. If we have 50 more products, each also
represented by its own unique id, are we supposed to create 50 more route definitions? Of course not. Fortunately, we
can deal with this situation, and others like it, using route parameters.


Figure 8-3. The route not found screen

Free download pdf