Dynamic Routing Using Angular JS

The need for Routing

Normally, when we create a multiple page application or website, we always need to navigate among various pages or views. With ASP.Net, we can do that using the window.redirect method. But in angularjs, we can do this using a Single Page Application. Single Page Applications are becoming very popular today due to phone/tablet apps. Angular JS helps to easily create applications like that.

Benefits of a Single Page Application

  1. Single Page Application.
  2. No Page refresh on page change.
  3. Multiple page data on the same page.

About Angular ngRoute

From AngularJS 1.2.0 routing has changed. It is now required that you explicitly import ngRoute in your applications.

  1. <script src=>  
  3. <script src="angular-route.js">  
Import the ngRoute module as in the following:
  1. angular.module('app', []);  
The ngRoute module provides routing and deep linking services and directives from any Angular JS Application.


ngView: The ngView directive displays the HTML templates or views in the specified routes. Every time the current route changes, the included view changes with it depending on the configuration of the $route service.

$routeProvider: The $routeProvider (provider in ngRoute Module) is used to configure the routes. We use the module's config() to configure the $routeProvider. The config() takes a function that takes the $routeProvider as parameter and the routing configuration goes inside the function. $routeProvider has a simple API, accepting either the when() or otherwise() method. $routeProvider.when() is used to match a URL pattern to a view whereas $routeProvider.otherwise() is used to render a view when there is no match to a URL pattern.

Why Dynamic Routing is Required

We can create routing using the following mentioned code in our web application:
  1. var module = angular.module("MyApp", ['ngRoute']);  
  2.     module.config(['$routeProvider',  
  3.         function($routeProvider) {  
  4.             $routeProvider.  
  5.                 when('/Home', {  
  6.                     templateUrl: 'Home.html',  
  7.                     controller: 'HomeController'  
  8.                 }).  
  9.                 when('/1st', {  
  10.                     templateUrl: 'First.html',  
  11.                     controller: 'FirstController'  
  12.                 }).  
  13.                 otherwise({  
  14.                     redirectTo: '/'  
  15.                 });  
  16.         }]);  
This process is OK if your web applicable contains a limited number of pages. But it becomes difficult when we have a large number of HTML files and we need to populate the navigation URL details depending on the user-defined rule, perhaps just like menus in a web application. In those case, we need to to configure the routeconfig dynamically by reading the data from an outer soure file (in other words from a database or JSON file) when we can change or rearrange the data as required.
For doing this, we declare a variable and assign that variable with routeProvider in app.Config. Then we read the data from the soure and generate a route string and assign that into the routeProvider variable in the app.Run. Becuase, in angular JS, the execution sequence of the app and their services are as follows:
  1. app.config
  2. app.run
  3. other services and directive compilation start
The following is the code block of the route config file:
  1. var $routeProviderReference;  
  3. MyApp.config(function ($routeProvider) {  
  4.     $routeProviderReference = $routeProvider;  
  5. });  
  7. MyApp.run(['$route''$http''$rootScope',  
  8.     function ($route, $http, $rootScope) {  
  9.         $http.get("../Script/User/routedata.json").success(function (data) {  
  10.             var iLoop = 0, currentRoute;  
  11.             for (iLoop = 0; iLoop < data.records.length; iLoop++) {  
  12.                 currentRoute = data.records[iLoop];  
  13.                 var routeName = "/" + currentRoute.KeyName;  
  14.                 $routeProviderReference.when(routeName, {  
  15.                     templateUrl: currentRoute.PageUrls  
  16.                 });  
  17.             }  
  18.             $route.reload();  
  19.         });  
  20.     }]);  
Now, we create a HTML file named HomePage.Html and write the following code. 
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title>Home Page</title>  
  5.     <script src="../Script/refScript/angular1.3.8.js"></script>  
  6.     <script src="../Script/refScript/angular-route.js"></script>  
  7.     <script src="../Script/User/MyApp.js"></script>  
  8.     <script src="../Script/User/DynaRoute.js"></script>  
  9.     <script src="../Script/User/HomeController.js"></script>  
  10.     <script src="../Script/User/FirstController.js"></script>  
  11.     <script src="../Script/User/SecondController.js"></script>  
  12.     <script src="../Script/User/ThirdController.js"></script>  
  13. </head>  
  14. <body ng-app="MyApp" ng-controller="HomeController">  
  15.     <table style="width:100%;">  
  16.         <tr>  
  17.             <td><a ng-click="fnGoToPage('home');">Home</a></td>  
  18.             <td><a ng-click="fnGoToPage('1st');">First Page</a></td>  
  19.             <td><a ng-click="fnGoToPage('2nd');">Second Page</a></td>  
  20.             <td><a ng-click="fnGoToPage('3rd');">Third Page</a></td>  
  21.         </tr>  
  22.     </table>  
  23.     <div class="pgHolder" ng-view>  
  24.     </div>  
  25. </body>  
  26. </html>  
Now, we declare the module of angular js for our project and store it in a file named MyApp.js as in the following:
  1. var MyApp = angular.module('MyApp', ['ngRoute']);  
Now, we create another file named routeData.json to store the route URL data.
  1. {  
  2.     "records": [  
  3.         {  
  4.             "KeyName""home",  
  5.             "PageUrls""../Html/Home.html",  
  6.             "Controller""HomeController"  
  7.         },  
  8.         {  
  9.             "KeyName""1st",  
  10.             "PageUrls""../Html/FirstPage.html",  
  11.             "Controller""FirstController"  
  12.         },  
  13.         {  
  14.             "KeyName""2nd",  
  15.             "PageUrls""../Html/SecondPage.html",  
  16.             "Controller""SecondController"  
  17.         },  
  18.         {  
  19.             "KeyName""3rd",  
  20.             "PageUrls""../Html/ThirdPage.html",  
  21.             "Controller""ThirdController"  
  22.         }  
  23.     ]  
  24. }  
The code for the HomeController is as in the following:
  1. MyApp.controller("HomeController", ['$scope''$http''$location',  
  2.     function ($scope, $http, $location) {  
  3.         $scope.fnGoToPage = function (args) {  
  4.             $location.path('/' + args);  
  5.         }  
  6.     }  
  7. ]);  
Now create another HTML file named FirstPage.Html and provide the following code for it:
  1. <div ng-controller="FirstController">  
  2.     {{Message1}}  
  3. </div>  
Now add a JavaScript file named FirstController.js and provide the following code for it:
  1. MyApp.controller("FirstController", ['$scope''$http',  
  2.     function ($scope, $http) {  
  3.         $scope.Message1 = "First page";  
  4.     }  
  5. ]);  
Now run your the application and click on the First Page Link on the home page.