Angular Router and UI-Router

In this article we will go through the next useful feature of AngularJS called Routing.Routing helps dividing our application in logical views and bind different views to Controllers.

What is $routeProvider?
Routing is taken care by a service provider that Angular provides out of the box called $routeProvider. An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function.

When we use AngularJS’s dependency injection and inject a service object in our Controller, Angular uses $injector to find corresponding service injector. Once it get a hold on service injector, it uses $get method of it to get an instance of service object. Sometime the service provider needs certain info in order to instantiate service object.

Application routes in Angular are declared via the $routeProvider, which is the provider of the $route service. This service makes it easy to wire together controllers, view templates, and the current URL location in the browser. Using this feature we can implement deep linking, which lets us utilize the browser’s history and bookmarks.

Basic router example:

<!DOCTYPE html>
<html>

  <head>
    <meta charset="UTF-8" />
    <title>$routeProvide example - CodePen</title>
  </head>

  <body>
    <div ng-app="pathApp" ng-controller="MainCtrl">

  Choose your option:
        <br />
      <br />
      <a href="/Book/Edit">Edit</a>
 |
        <a href="/Book/Delete">Delete</a>
 |
        <a href="/Book/Add">Add</a>
 |
        <a href="/Book/Show">Show</a>
      <div ng-view=""></div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.7/angular.min.js"></script>
    <script>angular.module('pathApp',[] ,function($routeProvider, $locationProvider){
  $routeProvider
  .when('/Book/Edit', {
    template: '<div>Edit</div>',
  })
  .when('/Book/Delete', {
    template: '<div>Delete</div>',
  })
  .when('/Book/Show', {
    template: '<div>Show</div>',
  })
  .when('/Book/Add', {
    template: '<div>Add</div>',
  })

  $locationProvider.html5Mode(true);

});

function MainCtrl($scope){
  $scope.test = "123";
}</script>
  </body>

</html>

Although the above example is a basic example of router. Still it describes the working procedure of router quite well. As we can see in the above html coding , that we have introduced four different links. They refer to the address to the ‘ $routeProvider’ inside the java script. In there we have a validation against particular chosen option.

What is AngularUI Router?

The UI-Router is a routing framework for AngularJS built by the AngularUI team. It provides a different approach than ngRoute in that it changes application views based on state of the application and not just the route URL.

States vs URL Route

Views and routes aren’t tied down to the site URL. This way, we can change the parts of our site using your routing even if the URL does not change.When using ngRoute, we have to use ngInclude or other methods and this could get confusing.

ui-router
ui-router fully embraces the state-machine nature of a routing system. It allows to define states, and transition to our application to those states. The real win is that it allows to decouple nested states, and do some very complicated layouts in an elegant way.
We should think about routing a bit differently, but once we get our head around the state-based approach,it will be much easier to make application.So, let’s look through a code to judge what is best.

In the below project we have used a few features to show a list of ice-creams and with their prices separately in a single page.

Index.html:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>
    <script src="app.js"></script>
  </head>
  <!-- apply our angular app to our site -->
  <body ng-app="routerApp">
    <!-- NAVIGATION -->
    <nav class="navbar navbar-inverse" role="navigation">
      <div class="navbar-header">
        <a class="navbar-brand" ui-sref="#">AngularUI Router</a>
      </div>
      <ul class="nav navbar-nav">
        <li>
          <a ui-sref="home">Home</a>
        </li>
        <li>
          <a ui-sref="about">About</a>
        </li>
      </ul>
    </nav>
       <div class="container">
      <div ui-view=""></div>
    </div>
     </body>
</html>

table-data.html:

<h2>Ice-Creams</h2>

<table class="table table-hover table-striped table-bordered">
    <thead>
        <tr>
            <td>Name</td>
            <td>Cost</td>
        </tr>
    </thead>
    <tbody>

        <tr ng-repeat="topic in topics">
            <td>{{ topic.name }}</td>
            <td>${{ topic.price }}</td>
        </tr>

    </tbody>
</table>

app.js:

var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/home');

    $stateProvider

        .state('home', {
            url: '/home',
            templateUrl: 'home.html'
        })

        // nested list with custom controller
        .state('home.list', {
            url: '/list',
            templateUrl: 'home-list.html',
            controller: function($scope) {
                $scope.topics = ['Butterscotch', 'Black Current', 'Mango'];
            }
        })

        // nested list with just some random string data
        .state('home.paragraph', {
            url: '/paragraph',
            template: 'I could sure use a scoop of ice-cream. '
        })

        .state('about', {
            url: '/about',
            views: {
                '': { templateUrl: 'about.html' },
                'columnOne@about': { template: '' },
                'columnTwo@about': { 
                    templateUrl: 'table-data.html',
                    controller: 'Controller'
                }
            }

        });

});

routerApp.controller('Controller', function($scope) {

    $scope.message = 'test';

    $scope.topics = [
        {
            name: 'Butterscotch',
            price: 50
        },
        {
            name: 'Black Current',
            price: 100
        },
        {
            name: 'Mango',
            price: 20
        }
    ];

});

about.html:

<div class="jumbotron text-center">
    <h1>The About Page</h1>
    <p>This page demonstrates <span class="text-danger">multiple</span> and <span class="text-danger">named</span> views.</p>
</div>
<div class="row">

    <div class="col-sm-6">
        <div ui-view="columnOne"></div>
    </div>
        <div class="col-sm-6">
        <div ui-view="columnTwo"></div>
    </div>
</div>

home.html:

<div class="jumbotron text-center">
    <h1>Home</h1>
    <p>This page demonstrates <span class="text-danger">nested</span> views.</p>
    <a ui-sref=".list" class="btn btn-primary">List</a>
    <a ui-sref=".paragraph" class="btn btn-danger">Paragraph</a>
</div>
<div ui-view></div>

home-list.html:

<ul>
    <li ng-repeat="topic in topics">{{ topic }}</li>
</ul>

In the above we have seen application of ui-router. But as we have said earlier in this article that without $stateprovider we can also initiate router in a different process. That is $routeprovider.

Below we are going to see an example where route is being initialized with $routeprovider. In the following example we will be working with a couple of links to other pages and the result they returns. Everything will be shown in a single page.

index.html:

<!DOCTYPE html>

<!-- define angular app -->
<html ng-app="scotchApp">

<head>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular-route.js"></script>
  <script src="script.js"></script>
</head>

<!-- define angular controller -->
<body ng-controller="mainController">

  <nav class="navbar navbar-default">
    <div class="container">
    <h1>Angular Routing Example with $routeprovider</h1>
           <ul class="nav navbar-nav navbar-right">
        <li><a href="#"><i class="fa fa-home"></i> Home</a></li>
        <li><a href="#about"><i class="fa fa-shield"></i> About</a></li>
        <li><a href="#contact"><i class="fa fa-comment"></i> Contact</a></li>
      </ul>
    </div>
  </nav>

  <div id="main">

    <!-- angular templating -->
		<!-- this is where content will be injected -->
    <div ng-view></div>

  </div>
  </body>
</html>

home.html:

<div class="text-center">
	<h1>Home Page</h1>

	<p>{{ message }}</p>
</div>

about.html:

<div class="text-center">
	<h1>Contact Page</h1>

	<p>{{ message }}</p>
</div>

contact.html:

<div class="text-center">
	<h1>About Page</h1>

	<p>{{ message }}</p>
</div>

script.js:

	// create the module and name it scotchApp
	var scotchApp = angular.module('scotchApp', ['ngRoute']);

	// configure our routes
	scotchApp.config(function($routeProvider) {
		$routeProvider

			// route for the home page
			.when('/', {
				templateUrl : 'home.html',
				controller  : 'mainController'
			})

			// route for the about page
			.when('/about', {
				templateUrl : 'about.html',
				controller  : 'aboutController'
			})

			// route for the contact page
			.when('/contact', {
				templateUrl : 'contact.html',
				controller  : 'contactController'
			});
	});

	// create the controller and inject Angular's $scope
	scotchApp.controller('mainController', function($scope) {
		// create a message to display in our view
		$scope.message = 'This is the home.';
	});

	scotchApp.controller('aboutController', function($scope) {
		$scope.message = 'Here you can know everything ABOUT us.';
	});

	scotchApp.controller('contactController', function($scope) {
		$scope.message = 'Contact us! For more information see below.';
	});

In the above applications we have used html5. Although we have not used any designing in these apps. Anyone can use bootstrap to their hearts content. These examples can only show how to work with routers in angularjs. These are some basic examples. We can also make many modifications as we fit to increase the performance.

Related Links:
1>Directive in Angular.js – Part 1
2>Directive in Angular.js – Part 2
3>Working with Modules in Angular.js
4>Angularjs and Services
5>Angular.js Promise
6>Angular.js Two Way Data Binding
7>How To Use Filter In Angular.js
8>Angular Templates
9>Using Controllers in Angular.Js
10>Angularjs with Server Side Interaction
11>Working Through Angular.js With Transclude
12>Angular.js Event Handling

If you find this article helpful, you can connect us in Google+ and Twitter.