Skip to content

Routing in AngularJS with Example

In this article, we are going to learn about Routing in AngularJS. In most of the applications, we see navigation/redirection between the content of the application. For example, in our daily life, we use many websites wherein if we click on some link/button we will be taken to somewhere from the current content page which is nothing but Routing. So let us try to understand how it is achieved in AngularJS. You are recommended to go through the Basic Building Blocks of AngularJS and Dependency Injection.

What is Routing?

Routing is the core feature of AngularJS. This feature helps in building a Single Page Application with multiple views where all views are simple HTML files. We use Routing to load different views or to navigate to the different parts of the application without loading an entire page again. It just updates the part of the page. It helps to divide an application logically and make it more understandable and readable.

In AngularJS, Routing is achieved in two ways. They are

ngRoute

The ngRoute module is used for Routing and it also provides deep-linking services and directives for AngularJS applications.

ngRoute Module Components

The ngRoute module includes the following components.

  • NgView: ngView is a directive that is used as a container for holding the rendered template of the current route in the main layout file(index.html). As every time the current route changes, the included template/view also changes according to the configuration of $route service.
  • $routeProvider: This is used for configuring the routes for an application.
  • $route: The $route service is used for mapping the URLs to controllers and views (HTML partials). It continuously watches the URL i.e $location.url() and tries to map the path to the existing route definition configured in the file.
  • $routeParams: The $routeParams service is used for retrieving the current set of route parameters.

In all angular applications, routes are configured or defined using $routeProvider. This is a provider of $route service. Using $route service, it is easy to link the controllers, view templates, and browser URLs. This routing configuration is done in a separate shared file of an application.

Route definition syntax is shown below.

  • $routeProvider.when(path, route);

path: This is the route path against which the $location.path is compared. This path can contain the parameters which are stored in $routeParams under the given name when the route matches.
route: This is an object which will hold all mapping information when the route matches.

This object will hold the following properties.

  1. controller: It can be a controller function or controller name.
  2. controllerAs: An identifier name (string) for a reference to the controller. This property is optional if the present controller is published to scope under the name “controllerAs”.
  3. template: It can be an HTML template written as a string or a function that returns an HTML template as a string.
  4. templateUrl: HTML template path as a string or a function that returns the path of an HTML template which is used by ngView.
  • $routeProvider.otherwise(params): It will set the route definition that will be used on route change when no other route definition is matched.

params: Mapping information to be assigned to $route.current. If called with a string, the value maps to redirectTo.

Example explaining Routing in AngularJS:

Let’s see a simple example of Routing in the Angular app using ngRoute.

In this example, we will have 3 simple links Home, About, and Contact.  When we click on any link it should load/navigate to other view templates i.e on click of Home, will be redirected to Home Page. On click of About, the user will be redirected to the About Page and likewise to the Contact page.

Let us build an app. We will have a file structure as shown below.

File structure to explain Routing in AngularJS
File structure

Step 1: First create the index.html page as shown below

<!DOCTYPE html>
<html>

<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

<!-- load angular via CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>

<body ng-app="myApp">
<h1>AngularJS Routing Example</h1>
<p>Click on the links to change the content.</p>
<ul>
	<li><a href="#home"><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 ng-view style='background-color:lightgrey;'></div>

</body>
</html>

In the above file as we can see that we have added a reference to angularJS version 1.2 via CDN to load the angular library. Also, we have added a reference to bootstrap and font awesome icons.

For implementing routing in angularJS, we have to use ngRoute.  To use ngRoute module we have to add a reference for this from CDN i.e angular-route.js file (you can see in the above code). And we have written code for having links for Home, About, and Contact.

Step 2:  To configure the routes and to write other logic, the script file is used. The following code explains script.js.

//create a module and name it as myApp

var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when('/home', {
        template : "<h2>Home</h2>Welcome to Home page!.</br></br>    {{message}}",
        controller:"mainController"
    })
    .when('/about', {
        template : "<h2>About</h2>Welcome to About page!."
    })
    .when('/contact', {
        template : "<h2>Contact</h2>Welcome to Contact page!."
    })
    .otherwise({
        template : "<p>Welcome to index page. This is the default page of this application.</p>"
    });
});

//create controller for home page and name it as mainController

app.controller('mainController', function($scope) {
        // create a message to display in our view
        $scope.message = 'This is simple message taken from mainController. Like this you can have separate controller for each view. Here we have template defined in the config itself but instead you can have different template and simply point to it using templateUrl property with its specific controller.';
    });

In the script file, we have written code for route configuration using $routeProvider.

To configure the routes, create a module named ‘myApp’ and add ‘ngRoute’  as a param to it. Now add a config to the ‘myApp’ module and pass ‘$routeProvider’ as a parameter. $routeProvider can be used only if we add a ngRoute reference to the angular module. Now using $routeProvider, the route definition is written for each view template.

You can have a controller for each view separately and you can implement the logic specific to the view. Here we have added mainController for the Home page just to show how we can add the controller.

And you can either use a template or templateUrl property. Usually, if the view template has more logic, then will go for the templateUrl property to look cleaner and readable. Since here it has less code, a template prop is used.

The output of the above example looks as shown below.

Initially, when the application is loaded, the output looks like the following. This is the index.html opened in the web browser.

Index page explaining Routing in AngularJS
index.html opened in the web browser

When the user clicks on the Home link, the output looks as shown in the below picture.

Routing example with link selected
Output when the Home link is sleeted

When the user clicks on Contact, the output looks like the one below.

Routing example with options selected
Output when the Contact link is selected

Conclusion:

This is how ngRoute is used for implementing Routing in a single-page app without any page reload. This is a built-in feature of AngularJS and most applications make use of it. Will see another approach in the next article.

Contributed by Preeti Dhavali.

Did it help? Would you like to express?