Saturday, May 10, 2014

Learning AngularJS Part 5: Routing or Views Switching

Here is Previous Part of this series:

So here we are with fifth part of the series, In previous article we see modularity and controller, config, factory of an AngularJS application. In this post we going to see routing or views switching in more details.

Why we need Routing?

First question here is why we need routing as we are working on Single Page Application (SPA). Answer is simple! yes we are working on SPA but user friendly URLs really help in reaching correct page instantly, it also help when your user bookmarks a particular view.

If we have our site and we are showing the same URLs for all of our page then if user bookmark this URL, on next visit he will again the same URL now your application really not know what user is expected view so application will show home page which is not user friendly way.

Instead this if we show or etc and attach these URL in your application to a particular view templates than it is really helpful and user-friendly.

So routing actually give a logical name to your application's views and bind them to a particular controller.

Routing URL - views and cotrollers
Routing -Views

How to route in AngularJS?

In previous post we have seen a bit of routing using ngRoute, but in this post we will see routing with UiRouter because UI Router is more powerful and is updated with more advanced feature along with basic functionality ngRoute provide, like Nested Views, multiple named view etc.

For setting routing, Firstly we nee uiRouter library you can download it from here or can use CDN hosted library then we need to add directive ng-view to the main (index.html) view.

<html ng-app="myDemoApp">
      Home About Us Contact US
</body> </html>

It work as a placeholder where all the html will be injected on a fly when particular url will be hit. For instance when user navigate to /#AboutUs , the view linked with AboutUs route will be injected to this placeholder, similarly other route will works.

Now we need add routes to config so we can associate views to urls and also while routing to views we pass the controller to the views.

//here we need to inject ui.router as we using it for routing
var myDemoApp = angular.module('myDemoApp', ['ui.router']);

//$stateprovider is the service procided by ui.router
myDemoApp.config(['$stateProvider', function ($stateProvider) {

//create route object
    var home= {
        url: '/home',
        templateUrl: 'views/Home.html',
        controller: 'HomeCtrl'
    aboutUs= {
        url: '/aboutus',
        templateUrl: 'views/AboutUs.html',
        controller: 'AboutUsCtrl'
    contactUs= {
        url: '/contactus',
        templateUrl: 'views/ContactUs.html',
        controller: 'ContactUsCtrl'

//Now add these route state privider

       .state('home', home)
       .state('aboutus', aboutUs)
       .state('contactUs', contactUs);

Now we add our views and place them in app/views/ folder also we need to add controllers to application module, if we do not need any controller like we just need to show some view which has nothing to show from controller then we can remove controller from above given object but usually each view has some controller to communicate. we can add controller like we have seen in previous post.

myDemoApp.controller('HomeCtrl', function ($scope) {
    $scope.message = 'Hello! we are on Home Page';
.controller('AboutUsCtrl', function ($scope) {
    $scope.message = 'Hello! we are on About Us Page';
.controller('ContactUsCtrl', function ($scope) {
    $scope.message = 'Hello! we are on Contact Us Page';

Now add three html files in views folder in app directory for each route and add html required in each view.


Now we have added everything we needed, save all files and try accessing url application with above configured urls. It must render particular views on different routes.

Master Pages in AngularJS

Master Page is the concept used in ASP.NET, It  is the base templates where we put all the common functionality which we need to show on all the pages, so instead repeating same code on all page we create a base page where we code required html, and inherit all pages from this base. Now all pages start showing within this template. These common views can be site log, top navigation, sidebar, logged in user information, footer etc.

We can also achieve this Master Page concept in AngularJS. Lets see it with an example:

Here in above example there are four different layers of views:
  1. Main View with Primar Navigation (Nav Link 1, Nav Link 2 ....)
  2. Second Level View with Sub-Navigation (One, Two, Three ...)
  3. Third Level View with Side Navigation (link1, link2, link3)
  4. Most inner View with content

To achieve this we define a hierarchy of routes.

For example:

  • /#NavLink1/One/Link1
  • /#NavLink2/One/Link1
  • /#NavLink1/Two/Link1
  • /#NavLink1/Two/Link2

and similarly for all other pages.

angular.module('demoMasterPage', ['ui.router'])
    .config(['$stateProvider', function ($stateProvider) {

    var NavLink1 = {
        //Name must be in format Parent.Child
        name: 'NavLink1',   
        url: '/Navlink1',
        templateUrl: 'views/Navlink1.html',
        controller: 'homeCtrl'
    NavLink2 = {
        name: 'NavLink2',
        url: '/Navlink2',
        templateUrl: 'views/Navlink2.html',
        controller: 'homeCtrl'
    NavLink3 = {
        name: 'NavLink3',
        url: '/Navlink3',
        templateUrl: 'views/Navlink3.html',
        controller: 'homeCtrl'

    NavLink1One = {
        name: 'NavLink1.One',
        url: '/Navlink1/One',
        templateUrl: 'views/Navlink1/One.html',
        controller: 'homeCtrl'
    NavLink1Two = {
        name: 'NavLink1.Two',
        url: '/Navlink1/Two',
        templateUrl: 'views/Navlink1/Two.html',
        controller: 'homeCtrl'

   // similarly for NavLink1Three,NavLink1Four, NavLink2One, NavLink2Two and so on.

    NavLink1OneLink1 = {
        name: 'NavLink1.One.Link1',
        url: '/Navlink1/One/Link1',
        templateUrl: 'views/Navlink1/One/Link1.html',
        controller: 'homeCtrl'
    NavLink1OneLink2 = {
        name: 'NavLink1.One.Link2',
        url: '/Navlink1/One/Link2',
        templateUrl: 'views/Navlink1/One/Link2.html',
        controller: 'homeCtrl'
    //Similarly define all the combination you want to separate

   //add routes to stateProvider
    $stateProvider.state('NavLink1', NavLink1)
        .state('NavLink2', NavLink2)
        .state('NavLink3', NavLink3)
        .state('NavLink1.One', NavLink1One)
        .state('NavLink1.Two', NavLink1Two)
        .state('NavLink1.One.Link1', NavLink1OneLink1)
        .state('NavLink1.One.Link2', NavLink1OneLink2);
.config(function ($urlRouterProvider) {
    //set default page to redirect; if wrong route is given redirect here    

Add different html pages for each views, If view contains a child view so we need to ng-view to that view, except level4 which has no further child views. Here is index.html:

<html ng-app="myDemoApp">
</body> </html>

NavLink1 will be a template injected in main index.html so we donot need to wrap it in html,body tags, Here is NavLink1:


Similarly One will contain navigation and ng-view so it can redirect to child views. Create all the pages and save them in right places and then try your application in browser and see the impact of different routes.

This above example can be optimized in many ways which you will learn as you have more experience in working with AngularJS

So hope now you have clear picture of routing in AngularJS if you have any confusion, question, suggestion or feedback please comment.

Here is Previous Part of this series:


  1. What happened to the rest of this series? You never got into the Factory/service side of things.

  2. Among many key features of AngularJS, routing is the technique using which we can design Single Page Application. Generally 2 things comes under this technique ng-view & ng-routing. ng-view act like a container where using routing we can load multiple templates. To make your journey easier here I am presenting more about routing with required examples

  3. Very Clear guide to learn angularjs. The clearness in your
    submit is just excellent and i can suppose you’re knowledgeable in this subject.

  4. Thanks for your article it will be helpful for me you can check codeignitor developer


Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,