---
title: "Explain Routing in AngularJS"  
description: "Routing in AngularJS facilitates navigation and view management in single-page applications."  
author: "Ashutosh Patel"  
published: 2024-06-21  
updated: 2024-06-21  
canonical: https://www.mindstick.com/blog/304405/explain-routing-in-angularjs  
category: "angular js"  
tags: ["javascript", "angular js", "angularjs routing"]  
reading_time: 5 minutes  

---

# Explain Routing in AngularJS

#### Angularjs Routing

In AngularJS, routing refers to a tool that allows you to define navigation paths in [your application](https://www.mindstick.com/forum/34702/please-tell-me-what-is-cross-site-scripting-and-how-is-it-harmful-for-your-application) and map them to specific **views** or **components** that should be displayed based on **URLs**. Routing is handled by the `ngRoute` module, which provides a convenient way to manage **single-page application** navigation.

#### Key Features of Routing

**Route [Configuration](https://www.mindstick.com/articles/13112/setting-up-the-perfect-configuration-for-your-work-computer) (**`$routeProvider`**):**

AngularJS uses `$routeProvider` to define the route of your application. Methods are set using the .when() method, where you specify a URL path and associated properties such as a controller template.

## Example

```javascript
angular.module('myApp', ['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider
            // when click on home page
            .when('/home', {
                templateUrl: 'views/home.html',
                controller: 'HomeController'
            })
            // when click on about page
            .when('/about', {
                templateUrl: 'views/about.html',
                controller: 'AboutController'
            })
            // default page load
            .otherwise({
                redirectTo: '/home'
            });
    });
```

\
**View Templates**\
Views or templates are HTML files that AngularJS loads based on the current path. These are specified using the `templateUrl` property in the method configuration or directly with the template property for inline **HTML**.

**Controllers**\
In AngularJS, controllers are responsible for processing the logic behind views. You can specify the controller for each route using the `controller` property of the route configuration.

**Directives**\
AngularJS directives can be used to bind data in templates, [handle events](https://www.mindstick.com/forum/157865/how-does-knockoutjs-handle-events-and-event-binding), or manipulate the DOM. Guides such as `ng-view` are used to dynamically rotate shapes based on the current path.

#### Routing Workflow

**Navigation**\
Users navigate through your application through links bound to AngularJS `ng-href` or `ng-click` directives, which update the browser's URL.

**Routing Process**\
When a [route changes](https://yourviews.mindstick.com/view/101/route-changes-alert-been-made-in-the-city), AngularJS matches the current URL with the routes defined in `$routeProvider`. It then loads the associated template and calls the specified controller.\
If no method matches the URL, the `.otherwise()` method converts to the default method.

**Single Page Application (SPA)**\
AngularJS [applications](https://www.mindstick.com/articles/12847/how-to-choose-the-right-ethernet-cable-for-industrial-applications) typically operate as SPAs, meaning that the entire application is loaded initially, and subsequent navigation and view updates are handled internally without reloading the entire page

**Also, Read:** [Create Custom Services in AngularJS](https://www.mindstick.com/blog/304402/create-custom-services-in-angularjs)

#### Benefits of routing in AngularJS

**Modularization** Routes allow you to modularize your application into specific views and controllers, making it easier to maintain and scale.

**SPA Behavior** Provides smooth access to the application without reloading the entire page, providing a more responsive experience.

**[SEO optimization](https://www.mindstick.com/blog/303534/handling-redirect-chains-and-loops-a-guide-to-seo-optimization)** While AngularJS primarily targets SPAs, server-side techniques or Angular Universal can be used for [SEO](https://www.mindstick.com/services/search-engine-optimization) purposes by rendering HTML first on the server.

## Example-

Here is a detailed example to explain the routing in angular js,

## Main Page (ng-route.html)

```html
<!DOCTYPE html>
<html data-ng-app="myApp">
<title>AngularJS Routing</title>
<!-- bootstrap cdn -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Angular js cdn -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<!-- Angular js routing cdn -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>
<body>
    <div class="container my-4">
        <div class="d-flex justify-content-between">
            <p class="ms-auto m-0 align-content-around">
                <span>
                    <a ng-href="#!home/"
                        class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover">Home</a>
                    <a ng-href="#!userdata"
                        class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover mx-1">UserData</a>
                    <a ng-href="#!posts"
                        class="link-offset-2 link-offset-3-hover link-underline link-underline-opacity-0 link-underline-opacity-75-hover  mx-1">Posts</a>
                </span>
            </p>
        </div>
        <hr class="m-1" />
        <!-- loads and bind the html file using ngRoute -->
        <div data-ng-view></div>
    </div>
    <!-- bind the javascript file -->
    <script src="main.js"> </script>
</body>
</html>
```

## Home.html page

```html
<div data-ng-controller="homeController">
    <div class="row" >
        <div class="col-12 my-4">
            <div class="text-center my-5">
                <p class="fs-1 fw-semibold p-2">Angular Routing Example</p>
                <div>
                    <p class="fw-5 ">
                        Here you learn about AngularJs Routing in details. Routing refers to the mechanism that allows you to define navigation paths within your application and map them to specific views or components that should be displayed based on the URL.
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
```

## ng-RouteUserData.html file

```html
<div data-ng-controller="userController">
    <div class="d-flex justify-content-between m-2">
        <p class="fs-5 fw-bold m-0">All Users</p>
        <p class="justify-content-end m-0">
            <span class="fw-semibold">Current Time: {{currTime}}</span>
        </p>
    </div>
</div>
```

## ng-RoutePosts.html file

```html
<div data-ng-controller="postController">
    <div class="row" >
        <div class="col-12">
            <h2>All Posts</h2>
            <hr />
        </div>
    </div>
</div>
```

**JavaScript file (main.js)**\
Add source in the main page (**ng-route.html**) file

```javascript
angular.module("myApp", ["ngRoute"])
        .controller("homeController", ["$scope", function($scope){
            console.log("Home page");
        }])
        .controller('userController',['$scope', '$http', '$interval', function($scope, $http, $interval){
            $interval(function(){
                $scope.currTime = new Date().toLocaleTimeString();
            });
        }])
        // Angular code for Posts.html page
        .controller('postController',['$scope', '$http', '$interval', function($scope, $http, $interval){
            $scope.currTime = new Date().toLocaleTimeString();
            $interval(function(){
                $scope.currTime = new Date().toLocaleTimeString()
            }, 1000);
        }])
        // Routing code for load view page
        .config(function($routeProvider){
            $routeProvider
            // home page
            .when('/home', {
                templateUrl: 'Home.html',
                controller: 'homeController'
            })
            // load when click on userdata
            .when('/userdata', {
                templateUrl : 'ng-RouteUserData.html',
                controller : 'userController'
            })
            // laod when click on posts
            .when('/posts', {
                templateUrl : 'ng-RoutePosts.html',
                controller : 'postController'
            });
            // default load for home page ng-route.html
            // .otherwise({
            //     redirectTo: '/'
            // });
        });
```

> Add all the above pages to the same folder

## Output-

![Explain Routing in AngularJS](https://www.mindstick.com/blogs/6a06d3f3-8387-4e2f-be57-e1c78d20f595/images/6a0d198f-6b28-40d4-aaf5-4602d178b257.png)\
\
Routing in AngularJS simplifies navigation and view management in single-page applications, allowing developers to create a structured and responsive [user experience](https://www.mindstick.com/articles/12731/the-importance-of-feedback-to-the-user-experience) through routing, view templates, and controller logic

**Also, Read:** [Custom Filters in AngularJS](https://www.mindstick.com/blog/304399/custom-filters-in-angularjs)

---

Original Source: https://www.mindstick.com/blog/304405/explain-routing-in-angularjs

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
