AngularJS From Beginning: Route Url - Part Nine

In this article, we will discuss how to use route concept in AngualrJS. This is part nine of the article series.

I am here to continue the discussion around AngularJS. Today, we will discuss about the routing concept in AngularJS. Also in case you have not had a look at our previous articles of this series, go through the following links:

In this article, I will discuss how AngularJS supports routing concept.

In this article, we will discuss about the URL routing features of AngularJS. AngularJS supports a feature called URL routing which uses the value returned by the $location.path method to load and display view files without the need for nasty literal values embedded throughout the markup and code in an application. But like other normal AngularJS features, this URL routing features not included by default in the AngularJS library files. So in the below sections, I will discuss how to download and install the $route service, which provides the URL routing functionally.

Installing the ngRoute Module

The $route service is defined within an optional module called ngRoute that must be downloaded into the angularjs folder. Go to http://angularjs.org, click Download, select the version you want and download the file. Download the angular-route.js file into the angularjs folder.

Defining the URL Routes

At the heart of the functionality provided by the $route service is a set of mappings between URLs and view file names, known as URL routes or just routes. When the value returned by the $location.path method matches one of the mappings, the corresponding view file will be loaded and displayed. The mappings are defined using the provider for the $route service, $routeProvider. Routes are defined using the $routeProvider.when method. The first argument is the URL that the route will apply to, and the second argument is the route configuration object. The routes I have defined are the simplest possible because the URLs are static and I have provided the minimum configuration information, but later in the article I’ll show you more complex examples. I’ll describe all of the configuration options later in the article, but for now it is enough to know that the templateUrl configuration option specifies the view file that should be used when the path of the current browser URL matches the first argument passed to the when method. In the below section, I show how to define a route config in AngularJS.

  1. testApp.config(function ($routeProvider) {  
  2.     
  3.     $routeProvider.when("/mobile", {  
  4.         templateUrl: "../ch09(route)/mobile.html",  
  5.         controller: "MobileController"  
  6.     });  
  7.   
  8. });  

Using Route Parameters

The URLs I used to define the routes in the previous section were fixed or static, meaning that the value passed to the $location.path method or set in an a element’s href attribute has to exactly match the value I used with the $routeProvider.when method. As a reminder, here is one of the routes that I defined:

  1. ...  
  2.   
  3. $routeProvider.when("/create", {  
  4.   
  5. templateUrl: "editorView.html"  
  6.   
  7. });  
  8.   
  9. ...  

This route will be activated only when the path component of the URL matches /create. This is the most basic kind of URL that routes can be used with and, as a consequence, the most limited. Route URLs can contain route parameters, which match one or more segments in the path displayed by the browser. A segment is the set of characters between two / characters. As an example, the segments in the URL http://localhost:5000/users/adam/details are users, adam, and details. There are two kinds of route parameters: conservative and eager. A conservative route parameter will match one segment, and an eager one will match as many segments as possible.

Accessing Routes and Routes Parameters

The URLs I used in the previous section process paths and assign the contents of segments to route parameters, which can then be accessed in code. In this section, I am going to demonstrate how to access those values using the $route and $routeParams services, both of which are contained in the ngRoute module.

Configuring Routes

The routes I have defined so far in this article have defined only the templateUrl configuration property, which specifies the URL of the view file that the route will display. This is only one of the configuration options available. I have listed the full set in below as follow.

Name Descriptions
controller Specifies the name of a controller to be associated with the view displayed by the Route
controllerAs Specifies an alias to be used for the controller.
Template Specifies the content of the view. This can be expressed as a literal HTML string or as a function that returns the HTML.
templateUrl Specifies the URL of the view file to display when the route matches. This can be expressed as a string or as a function that returns a string
resolve Specifies a set of dependencies for the controller
redirectTo Specifies a path that the browser should be redirected to when the route is matched. Can be expressed as a string or a function

For demonstrating the route concept, I write down the below code as mentioned : 

app.js
  1. var testApp = angular.module('TestApp', ['ngRoute']);  
  2.   
  3. testApp.config(function ($routeProvider) {  
  4.     
  5.     $routeProvider.when("/mobile", {  
  6.         templateUrl: "../ch09(route)/mobile.html",  
  7.         controller: "MobileController"  
  8.     });  
  9.     $routeProvider.when("/tv/:rebate", {  
  10.         templateUrl: "../ch09(route)/tv.html",  
  11.         controller: "TVController"  
  12.     });  
  13.     $routeProvider.when("/computer", {  
  14.         templateUrl: "../ch09(route)/computer.html",  
  15.         controller: "ComputerController"  
  16.     });  
  17.     $routeProvider.otherwise({  
  18.         templateUrl: "../ch09(route)/home.html",  
  19.         controller: "HomeController"  
  20.     });  
  21. });  
Index.html
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title>Home Page For Route</title>  
  5.     <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />  
  6.     <script src="angular.js"></script>  
  7.     <script src="angular-route.js"></script>  
  8.     <script src="app.js"></script>  
  9.     <script src="IndexController.js"></script>  
  10.     <script src="HomeController.js"></script>  
  11.     <script src="MobileController.js"></script>  
  12.     <script src="TVController.js"></script>  
  13.     <script src="ComputerController.js"></script>  
  14. </head>  
  15. <body ng-app="TestApp" ng-controller="IndexController">  
  16.     <div class="rowDiv panel panel-primary">  
  17.         <h2 class="panel-heading">Demostration of Angular Rute Concept</h2>  
  18.         <table style="width:40%;">  
  19.             <tr class="table-bordered">  
  20.                 <td><a ng-click="fnGoToPage('home');" class="btn-block">Home</a></td>  
  21.                 <td><a ng-click="fnGoToPage('mobile');">Mobile</a></td>  
  22.                 <td><a ng-click="fnGoToPage('tv');">TV</a></td>  
  23.                 <td><a ng-click="fnGoToPage('computer');">Computers</a></td>  
  24.             </tr>  
  25.         </table>  
  26.   
  27.     </div>  
  28.     <div class="rowDiv navbar-form">  
  29.         <div class="pgHolder" ng-view>  
  30.         </div>  
  31.     </div>  
  32. </body>  
  33. </html>  
IndexController.js
  1. testApp.controller("IndexController", ['$scope''$http''$location',  
  2.     function ($scope, $http, $location) {  
  3.         $scope.fnGoToPage = function (args) {  
  4.   
  5.             if (args == 'tv') {  
  6.                 $location.path('/' + args + "/10%");  
  7.             }  
  8.             else  
  9.                 $location.path('/' + args);  
  10.         }  
  11.     }  
  12. ]);  
Home.html 
  1. <div class="row">  
  2.     <p class="panel-body">  
  3.         Home Page  
  4.         <br />  
  5.         <h3 class="panel-heading">{{Message}}</h3>  
  6.     </p>  
  7. </div>  
HomeController.js
  1. testApp.controller("HomeController", ['$scope''$http',  
  2.     function ($scope, $http) {  
  3.         $scope.Message = "Click link to move other page";  
  4.     }  
  5. ]);  
Mobile.html
  1. <div class="panel-body">  
  2.     <table class="table table-striped table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Name</th>  
  6.                 <th>Company</th>  
  7.                 <th class="text-right">Quantity</th>  
  8.                 <th class="text-right">Price</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             <tr ng-repeat="item in data">  
  13.                 <td>{{item.name}}</td>  
  14.                 <td>{{item.company}}</td>  
  15.                 <td class="text-right">{{item.quantity}}</td>       
  16.                 <td class="text-right">{{item.price | currency}}</td>                  
  17.             </tr>  
  18.         </tbody>  
  19.     </table>  
  20. </div>  
MobileController.js
  1. testApp.controller("MobileController", ['$scope''$http',  
  2.     function ($scope, $http) {  
  3.         $scope.data = [ { name: 'Galaxy Tab 3', company: 'Samsung', quantity: '10', price: '25000.00' },  
  4.                         { name: 'Galaxy Tab 5', company: 'Samsung', quantity: '50', price: '55000.00' },  
  5.                         { name: 'G4', company: 'LG', quantity: '10', price: '40000.00' },  
  6.                         { name: 'Canvas 3', company: 'Micromax', quantity: '25', price: '18000.00' }];  
  7.     }  
  8. ]);  
Tv.html
  1. <div class="panel-body">  
  2.     <h2 class="panel-heading">All Products have special discount of {{rebate}}</h2>  
  3.     <table class="table table-striped table-bordered">  
  4.         <thead>  
  5.             <tr>  
  6.                 <th>Name</th>  
  7.                 <th>Company</th>  
  8.                 <th class="text-right">Quantity</th>  
  9.                 <th class="text-right">Price</th>  
  10.             </tr>  
  11.         </thead>  
  12.         <tbody>  
  13.             <tr ng-repeat="item in data">  
  14.                 <td>{{item.name}}</td>  
  15.                 <td>{{item.company}}</td>  
  16.                 <td class="text-right">{{item.quantity}}</td>       
  17.                 <td class="text-right">{{item.price | currency}}</td>                  
  18.             </tr>  
  19.         </tbody>  
  20.     </table>  
  21. </div>  
TVController.js
  1. testApp.controller("TVController", ['$scope''$http','$routeParams',  
  2.     function ($scope, $http, $routeParams) {  
  3.         $scope.rebate = $routeParams.rebate;  
  4.   
  5.         $scope.data = [ { name: 'LED TV 20"', company: 'Samsung', quantity: '10', price: '11000.00' },  
  6.                         { name: 'LED TV 24"', company: 'Samsung', quantity: '50', price: '15000.00' },  
  7.                         { name: 'LED TV 32"', company: 'LG', quantity: '10', price: '32000.00' },  
  8.                         { name: 'LED TV 48"', company: 'SONY', quantity: '25', price: '28000.00' }];  
  9.     }  
  10. ]);  
Computer.html
  1. <div class="panel-body">  
  2.     <table class="table table-striped table-bordered">  
  3.         <thead>  
  4.             <tr>  
  5.                 <th>Name</th>  
  6.                 <th>Company</th>  
  7.                 <th class="text-right">Quantity</th>  
  8.                 <th class="text-right">Price</th>  
  9.             </tr>  
  10.         </thead>  
  11.         <tbody>  
  12.             <tr ng-repeat="item in data">  
  13.                 <td>{{item.name}}</td>  
  14.                 <td>{{item.company}}</td>  
  15.                 <td class="text-right">{{item.quantity}}</td>       
  16.                 <td class="text-right">{{item.price | currency}}</td>                  
  17.             </tr>  
  18.         </tbody>  
  19.     </table>  
  20. </div>  
ComputerController.js
  1. testApp.controller("ComputerController", ['$scope''$http',  
  2.     function ($scope, $http) {  
  3.         $scope.data = [ { name: 'HP Pavilion 15"', company: 'HP', quantity: '10', price: '42000.00', specification:'Intel Core i3 2 GB Ram 500 GB HDD with Windows 10' },  
  4.                         { name: 'Lenovo Flex 2"', company: 'Lenovo', quantity: '20', price: '32000.00', specification: 'Intel Core i3 2 GB Ram 500 GB HDD with DOS OS' },  
  5.                         { name: 'Lenovo Yova 500"', company: 'Lenovo', quantity: '20', price: '70000.00', specification: 'Intel Core i7 8 GB Ram 1TB HDD with Windows 8.1' }];  
  6.     }  
  7. ]);  
Now run the program and the output as below -