Objectives and outcomes

In this tutorial we are going to learn about routing in angular-js, which is most likely similar to angular-js http service (Learn angularjs http service). It also helps in achieving the purpose of single page application (SAP). Routing content is displayed using either ng-view or ng-template directives. In this tutorial we are going to use routing with ng-view.

Note: To use the routing service in your application we need to link angular-route.js file to the application.


var app = angular.module("route_app", ["ngRoute"]);
templateUrl : "/route2.html",
controller : "route2_control"
templateUrl : "/route3.html",
controller : "route3_control"
templateUrl : "/route1.html"

app.controller("route2_control", function ($scope) 
$scope.message = "This message is from route2 controller.";
app.controller("route3_control", function ($scope) 
$scope.message = "This message is from route3 controller.";

HTML code

<meta charset="utf-8">
<title>AngularJS Routing</title>
<script src="angular-1.4.6/angular.min.js"></script>
<script src="angular-1.4.6/angular-route.min.js"></script>
<div class="row" ng-app="route_app" >
<a href="#/">Route1</a><br/>
<a href="#/route2">Route2</a><br/>
<a href="#/route3">Route3</a><br/>   
<div ng-view></div> 

HTML for route1.html

<p>This paragraph is from route1.html file</p>

HTML for route2.html

<p>This paragraph is from route2.html file and <b>{{message}}</b></p>

HTML for route3.html

<p>This paragraph is from file route3.html and <b>{{message}}</b></p>

Click on the given below link and observe the effect.

All the routing task is defined inside config function. ngRoute is used to route the application to different pages by matching the url pattern inside the when function. The otherwise function is called when no pattern match is found. We have to provide the correct path to the templateUrl and we can also declare the controller for the page which is called. An application can have only single ng-view container.