Routing In AngularJS

Introduction

Routing is a core feature in AngularJS. This feature is useful in building SPA (Single Page Application) with multiple views. In SPA application, all views are different Html files and we use Routing to load different part of application and its help to divide application logically and make it manageable. In other words, Routing helps us to divide our application in logical views and bind them with different controllers.

Routing

In the above diagram, I have created two routes URL and each points to a specific view managed by a specific controller. In the later part of the article, we will learn how it works=s.

Introduction to ngRoute Module

This module provides routing in AngularJS application and also provides deep linking services and directives. To achieve routing in AngularJS, we need to include the library file of ngRoute.

Component of ngRoute Module

There are four main components of ngRoute module:

  • ngView: ngView is directive and creates new scope. It is used to load html templates.

  • $routeProvider: It is used to configure routes.

  • $route: It is used to make deep linking URLs between controllers and view. $route watches $location.url() and tries to map the path to an existing route defined by $routeProvider.

  • $routeParams: This is Angular service which allows us to retrieve the current set of route parameters.

$routeProvider used for configuring the routes in AngularJS application. It is depends on ngRoute module. All application routes are defined via $routeProvider and it is the provider of the $route Service. It is very easy to wire up controllers, view templates and browser URL location using $route service. This service also help us to implement deep linking that utilize the browser back and forward navigation (browser’s history).

Hello World Example

Routing in AngularJS is used to load different templates at runtime. In the following example we will elaborate it more step by step.

Step 1: Create basic structure of application (SPA).

In this step, I have created demo.html and it includes all the required AngularJS library and bootstrap library. Here I have also created structure for application. Also defined two links: page1 and page2. Each link loads respective template.

Project structure

Project structure

Demo.html

  1. <!DOCTYPEhtml>  
  2. <htmldata-ng-apphtmldata-ng-app="AngularApp">  
  3.   
  4.     <head>  
  5.         <metacontentmetacontent="IE=edge, chrome=1" http-equiv="X-UA-Compatible" />  
  6.         <title>AngularJS - Routing</title>  
  7.         <scriptsrcscriptsrc="angular.js">  
  8.             </script>  
  9.             <scriptsrcscriptsrc="angular-route.js">  
  10.                 </script>  
  11.                 <scriptsrcscriptsrc="app.js">  
  12.                     </script>  
  13.                     <scriptsrcscriptsrc="jquery-1.10.2.min.js">  
  14.                         </script>  
  15.                         <scriptsrcscriptsrc="DemoController.js">  
  16.                             </script>  
  17.                             <scriptsrcscriptsrc="Modules/Page1/Page1Controller.js">  
  18.                                 </script>  
  19.                                 <scriptsrcscriptsrc="Modules/Page2/Page2Controller.js">  
  20.                                     </script>  
  21.                                     <scriptsrcscriptsrc="bootstrap.min.js">  
  22.                                         </script>  
  23.                                         <linkhreflinkhref="bootstrap.min.css" rel="stylesheet" /> </head>  
  24.   
  25.     <body>  
  26.         <div>  
  27.             <div ng-controller="demoController" class="container">  
  28.                 <p><b>Hello World - Routing Example</b></p>  
  29.                 <divclassdivclass="row">  
  30.                     <divclassdivclass="col-md-3">  
  31.                         <ulclassulclass="nav">  
  32.                             <li>  
  33.                                 <ahrefahref="#/page1"> Page 1 </a>  
  34.                             </li>  
  35.                             <li>  
  36.                                 <ahrefahref="#/page2"> Page 2 </a>  
  37.                             </li>  
  38.                             </ul>  
  39.             </div>  
  40.             <divclassdivclass="col-md-9">  
  41.                 <divng-view>  
  42.         </div>  
  43.         </div>  
  44.         </div>  
  45.         </div>  
  46.         </div>  
  47.     </body>  
  48.   
  49. </html>  
Here I have divided screen in two sections: Left contains the menu and in the right pane respective template will be loaded.

The ngView directive is responsible to render the template of current route into the main layout file passed by $route service. I have also defined ng-app directive once. The ngView become place holder for views. Every view render by the route is loaded into this section.

Step 2: Add Routing

In the Demo.html, I have included app.js file which hold the definition of AngularJS application. The $routeProvider definition contain by the module is called "ngRoute". In app.js file, I have defined an angular app using “angular. Module” method. After creating module, we need to configure the routes. The "config" method is used to configure $routeProvider. Using "when" and "otherwise" method of $routeProvider, we can define the route for our AngularJS application.

app.js
  1. var app = angular.module("AngularApp", ['ngRoute']);  
  2. app.config(['$routeProvider',  
  3.     function ($routeProvider)  
  4.     {  
  5.         $routeProvider.  
  6.         when('/page1',  
  7.             {  
  8.                 templateUrl: 'Modules/Page1/page1.html',  
  9.                 controller: 'Page1Controller'  
  10.             })  
  11.             .  
  12.         when('/page2',  
  13.             {  
  14.                 templateUrl: 'Modules/Page2/page2.html',  
  15.                 controller: 'Page2Controller'  
  16.             })  
  17.             .  
  18.         otherwise(  
  19.         {  
  20.             redirectTo: '/page1'  
  21.         });  
  22.     }  
  23. ]);  
In the above code, I have defined two routes: "page1" and "page2" and mapped them with template view "Modules/Page1/page1.html" and "Modules/Page2/page2.html" respectively. I have set default page using "otherwise" method.

Step 3: Define HTML Template and controller

In this example, I have added two html templates: page1.html and page2.html and created two controllers files: page1controller.js and page2controller.js. The following are the definition of both HTML template and controller.

Page1.html
  1. <divng-controller="Page1Controller">  
  2.     <h2>Page 1</h2> Hi, {{myName}} </div>  
Page1Controller.js
  1. app.controller("Page1Controller", ['$scope', function ($scope)  
  2. {  
  3.     $scope.myName = "Tejas Trivedi";  
  4. }]);  
Page2.html
  1. <divng-controller="Page2Controller">  
  2.     <h2>Page 2</h2> Hi, {{myName}} </div>  
Page1Controller.js
  1. app.controller("Page2Controller", ['$scope', function ($scope)  
  2. {  
  3.     $scope.myName = "Jignesh Trivedi";  
  4. }]);  
Output

Page1Controller

Pass parameters to route URL

We can also define parameters in the route URL. Parameter name should define by colon (:) after the route path. The $routeParams service allow us to retrieve the route parameters in controller.

This feature is useful when we want to use same view for two or more different purpose and it can be identified by the parameter value or we want to display detail of any master record based on master id and master id passed as parameter. In Angular, route parameter can be defined using parameter name in URL. For example,

app.js
  1. .when('/page3/:id',  
  2. {  
  3.     templateUrl: 'Modules/Page3/page3.html',  
  4.     controller: 'Page3Controller'  
  5. })  
We can read parameter value in controller by using $routeParams. Note that do not forget to inject $routeParam service in controller.

page3Controller.js
  1. app.controller("Page3Controller", ['$scope''$routeParams', function ($scope, $routeParams)  
  2. {  
  3.     $scope.myName = "Jignesh Trivedi";  
  4.     $scope.id = $routeParams.id;  
  5. }]);  
page3.html
  1. <divng-controller="Page2Controller">  
  2.     <h2>Page 3</h2> My Id : {{id}} </div>  
Demo.html

Demo

Output

Output

Load local views

This is not always required to load view from the different html files because view templates are very small and we might want to keep them within main html file instead of creating separate html files. The ng-template can be used to define small templates in the main html file.

Syntax

<script type="text/ng-template" id="page4.html">
   //define definition of html here...
</script>


Here I have defined a template "page4.html" and "page5.html" inside the script tag. AngularJS will automatically load these templates in ng-view when "page4.html" or "page5.html" is referred in route.

DemoLocalView.html defines the structure of the application. The appLocalView.js is very similar to previous example. Here I have used same controller js files.

appLocalView.js
  1. var app = angular.module("AngularApp", ['ngRoute']);  
  2. app.config(['$routeProvider',  
  3.     function ($routeProvider)  
  4.     {  
  5.         $routeProvider.  
  6.         when('/page4',  
  7.             {  
  8.                 templateUrl: 'page4.html',  
  9.                 controller: 'Page1Controller'  
  10.             })  
  11.             .  
  12.         when('/page5',  
  13.             {  
  14.                 templateUrl: 'page5.html',  
  15.                 controller: 'Page2Controller'  
  16.             })  
  17.             .  
  18.         otherwise(  
  19.         {  
  20.             redirectTo: '/page4'  
  21.         });  
  22.     }  
  23. ]);  
DemoLocalView.html
  1. <!DOCTYPE html>  
  2. <html data-ng-app="AngularApp">  
  3.   
  4.     <head>  
  5.         <meta content="IE=edge, chrome=1" http-equiv="X-UA-Compatible" />  
  6.         <title>AngularJS - Routing</title>  
  7.         <script src="angular.js"></script>  
  8.         <script src="angular-route.js"></script>  
  9.         <script src="appLocalView.js"></script>  
  10.         <script src="jquery-1.10.2.min.js"></script>  
  11.         <script src="Modules/Page1/Page1Controller.js"></script>  
  12.         <script src="Modules/Page2/Page2Controller.js"></script>  
  13.         <script src="bootstrap.min.js"></script>  
  14.         <link href="bootstrap.min.css" rel="stylesheet" /> </head>  
  15.   
  16.     <body>  
  17.         <div>  
  18.             <div class="container">  
  19.                 <p><b>Load local view Example</b></p>  
  20.                 <div class="row">  
  21.                     <div class="col-md-3">  
  22.                         <ul class="nav">  
  23.                             <li><a href="#page4"> Page 4 </a></li>  
  24.                             <li><a href="#page5"> Page 5 </a></li>  
  25.                         </ul>  
  26.                     </div>  
  27.                     <div class="col-md-9">  
  28.                         <div ng-view></div>  
  29.                     </div>  
  30.                 </div>  
  31.                 <script type="text/ng-template" id="page4.html">  
  32.                     <h2> Page 4 </h2> Hi, {{myName}} </script>  
  33.                 <script type="text/ng-template" id="page5.html">  
  34.                     <h2> Page 5 </h2> Hi, {{myName}} </script>  
  35.             </div>  
  36.         </div>  
  37.     </body>  
  38.   
  39. </html>  
Output

run

Conclusion

This article helps us to know routing in AngularJS.

Up Next
    Ebook Download
    View all
    Learn
    View all