Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Easy

AngularJS Routing

gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

In this article, we will learn routing in AngularJS. Routing refers to mapping URLs to specific views and controllers in a single-page application. In AngularJS, routing allows users to map URLs to specific views and controllers. So that when a user navigates to a particular URL, the corresponding view and controller are loaded.

AngularJS routing

We require the ngRoute module to implement AngularJS routes. So let us learn about the ngRoute module.

What is the ngRoute module?

The ngRoute module is a part of the AngularJS framework that provides routing and deep linking services and directives for AngularJS apps. This module enables us to implement routing in AngularJS. 

What is the ngRoute module?

The ngRoute module is typically used in conjunction with the $route service and the ng-view directive. The $route service matches the current URL to a corresponding route definition and instantiates the appropriate controller and view. The ng-view directive is used as a placeholder in the HTML template for the view associated with the current route.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax

The syntax for the AngularJS routes is as follows:

// including the ngRoute module
var app = angular.module("myApp", ["ngRoute"]);

/*
    We will see the two methods of $routeProvider
    when() and otherwise()
*/
app.config(function($routeProvider) {
    $routeProvider

        .when("/", {
            templateUrl: < filename > ,
            Template: < HTML template >
                controller: < controllername >
        })

        .otherwise({
            templateUrl: < filename > ,
            controller: controllername
        })
});

 

In the upcoming sections of this article, we will thoroughly understand each and every line of this syntax code.

Understanding the Syntax

Let us understand the above-stated syntax. First of all, we will discuss the setup required for AngularJS routing.

Setup Required

For the setup, we will first include the AngularJS routes module in our application.

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

 

To get started with the use of the AngularJS routes, we must include the ngRoute module.

var myApp = angular.module("myApp", ["ngRoute"]);

 

$routeProvider

By using the AngularJS routes, we get $routeProvider. Then our next step is to configure routes using the $routeProvider service. 

There are two methods of $routeProvider. They are:

  • when()
  • otherwise()

when() method

The when() method of the $routeProvider service in AngularJS is used to define a route for the application. The when() method takes two arguments: first is a string representing the URL pattern for the route. The second argument is an object containing the route configuration options.

The route configuration options can include the following properties:

  • template: the HTML template to be rendered for the route.
  • templateUrl: the URL of the HTML template to be rendered for the route.
  • controller: the AngularJS controller to be associated with the route.
  • redirectTo: a URL to redirect to if the route is accessed.

These configurations are all optional in nature.

$routeProvider.when("/", {
            templateUrl: < filename > ,
            Template: < HTML template >
            controller: < controllername >
        })

 

We can chain multiple when() methods together to define multiple routes. Each when() method maps a URL pattern to a specific template and controller. When the user navigates to a specific URL, AngularJS uses the $route service to match the URL to a corresponding route definition and then loads the appropriate view and controller.

otherwise() method

The otherwise() method of the $routeProvider service in AngularJS is used to define a fallback route for the application. We use this method to handle cases where the user navigates to a URL that does not match any of the routes defined using the when() method. 

The otherwise() method takes one argument, which is either a string representing the URL to redirect to or a route configuration object, similar to the one passed to the when() method.

$routeProvider.otherwise(routeConfig);

 

As we discussed, routeConfig can be either a string or an object.

If routeConfig is a string, it should be a URL to redirect to:

$routeProvider.otherwise('/URL');

 

If routeConfig is an object, it should contain a configuration similar to the one passed to the when() method, such as template, templateUrl, controller, and redirectTo:

$routeProvider.otherwise({
    templateUrl: < file name >,
    controller: < controller name >
});

 

It's important to note that the otherwise() method should be called after all the when() methods. Else, it won't work as expected.

It's also worth noting that the otherwise() method is optional, and it's not necessary to define it in the application. But it's a best practice to have a fallback route in case of unexpected routes to avoid any unexpected errors.

Important Note

When using AngularJS Roues in the HTML template, we must include the ng-view directive to define the container for the views. This is because the application requires a container to put the output given by the routes.

<div ng-view></div>

Example

Now, after a deep discussion of the syntax, we will see an example to check our understanding.

Code

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
    </head>
    <body ng-app="myApp">
        <p>
            <a href="#/!">
        <h3>Home</h3></a>
        <a href="#!blogs">
            <h3>Blogs Section</h3>
        </a>
        <a href="#!about">
            <h3>About Coding Ninjas Studio</h3>
        </a>
        </p>
        <div ng-view></div>
        <script>
            const app = angular.module("myApp", ["ngRoute"]);
            app.config(function ($routeProvider) {
             $routeProvider
                       .when("/", {
                           template: `<h1>We welcome you all to Coding Ninjas Studio.</h1>`
                          })
             .when("/blogs", {
             template: `<h1>Blogs Section</h1>
             <p>
             <ul>
             <li>Data Structures and Algorithms</li>
             <li>Computer Fundamentals</li>
             <li>Other vital Topics</li>
             </ul>
             </p>`
             })
             .when("/about", {
             template: `<h1>We are Coding Ninjas</h1>
             				<p>
                            	World has enough coders, be more than that. Be a <b>CODING NINJA</b>
                            </p>`
             })
             .otherwise({
             template: `<h1>Please Select Something!</h1>
             				<p>
             					Nothing has been selected yet
             				</p>`
             });
            });
        </script>
    </body>
</html>

Output

On opening our home page we get this.

Output 1

 

When we click on the blogs section, we will get the below output.

Output 2

 

When we click on about coding ninjas, we will get this output.

Output 3

Explanation

In this example, we see the proper use of AngularJS routes. We have created three routes using the when() method of the routeProvider service. One for home, one for the blog section, and one for the about section. We have also created an otherwise() method to keep a check on all the corner cases. So, whenever there is any rollback, we output the error message. 

Frequently Asked Questions 

What is routing in AngularJS?

In AngularJS, routing allows users to map URLs to specific views and controllers. So that when a user navigates to a certain URL, the corresponding view and controller are loaded.

What is the ngRoute module?

The ngRoute module is a part of the AngularJS framework that provides routing and deep linking services and directives for AngularJS apps.

What is routeProvider?

It is a service of AngularJS routes that enables us to use two types of methods named when and otherwise.

What types of arguments can be taken by the otherwise() method?

Two types of arguments can be taken by the otherwise() method: a string representing the URL to redirect to or a route configuration object.

What is the need for ng-view?

We need the ng-view directive to define the container for the views. This is because the application requires a container to put the output given by the routes.

Conclusion

In this article, we learned about routing in AngularJS. We learned how to set up the routes. We also discussed all the methods essential for routing.

Check out our articles if you think this blog has helped you enhance your knowledge and want to learn more. Visit our website to read more such blogs. 

  1. Introduction to AngularJS  
  2. React vs. Angular  
  3. Angular js vs. Nodejs 
  4. Difference between Angular and AngularJs 
  5. AngularJs Library 

 

For placement preparations, you must look at the problemsinterview experiences, and interview bundles. Enrol in our courses and refer to the mock tests and problems available; look at the Problem Sheets interview experiences, and interview bundle for placement preparations. You can also book an interview session with us.  

Consider our paid courses, however, to give your career a competitive advantage!

Happy Coding!

Previous article
AngularJS Includes
Next article
AngularJS - Application
Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass