---
title: "How does routing work in AngularJS?"  
description: "How does routing work in AngularJS?"  
author: "Sandra Emily"  
published: 2024-06-24  
updated: 2024-06-25  
canonical: https://www.mindstick.com/forum/160771/how-does-routing-work-in-angularjs  
category: "angular js"  
tags: ["web development", "angular js", "front-end development"]  
reading_time: 4 minutes  

---

# How does routing work in AngularJS?

How does [routing work in AngularJS](https://www.mindstick.com/forum/157878/how-does-routing-work-in-angularjs-and-what-are-some-common-use-cases)?

## Replies

### Reply by Ravi Vishwakarma

[Routing in AngularJS](https://www.mindstick.com/blog/304405/explain-routing-in-angularjs) is a feature that allows developers to create [single-page applications (SPAs)](https://www.mindstick.com/articles/336207/single-page-application-in-angularjs) with multiple views. This means that different views can be loaded without refreshing the entire web page. AngularJS handles routing through the `ngRoute` module, which provides the `$routeProvider` service to configure routes. Here’s an overview of how routing works in AngularJS:

#### Setting Up Routing

**Include the AngularJS and ngRoute Libraries**: First, include AngularJS and the `ngRoute` script in your HTML file.

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

**Create the AngularJS Application Module**: Define your AngularJS application module and include `ngRoute` as a dependency.

```javascript
var app = angular.module('myApp', ['ngRoute']);
```

**Configure Routes**: Use the `$routeProvider` service to define routes within the configuration block of your application module.

```javascript
app.config(['$routeProvider', function($routeProvider) {
            $routeProvider
                .when('/home', {
                    templateUrl: '../home.html',
                    controller: 'HomeController'
                })
                .when('/about', {
                    templateUrl: '../about.html',
                    controller: 'AboutController'
                })
                .otherwise({
                    redirectTo: '/home'
                });
        }]);
```

**Create Controllers and Views**: Define the controllers and views corresponding to each route.

```javascript
app.controller('HomeController', ['$scope', function($scope) {
    $scope.message = "Welcome to the Home Page";
}]);

app.controller('AboutController', ['$scope', function($scope) {
    $scope.message = "Learn more About Us";
}]);
```

## <!-- home.html -→

```html
<div class="text-center">
    <h1>Welcome to the Home Page!</h1>
</div>

<div id="carouselExampleCaptions" class="carousel slide">
    <div class="carousel-indicators">
      <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
      <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button>
      <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button>
    </div>
    <div class="carousel-inner">
      <div class="carousel-item active">
        <img src="https://images.pexels.com/photos/460621/pexels-photo-460621.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" class="d-block w-100" alt="...">
        <div class="carousel-caption d-none d-md-block">
          <h5>First slide label</h5>
          <p>Some representative placeholder content for the first slide.</p>
        </div>
      </div>
      <div class="carousel-item">
        <img src="https://images.pexels.com/photos/1379640/pexels-photo-1379640.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" class="d-block w-100" alt="...">
        <div class="carousel-caption d-none d-md-block">
          <h5>Second slide label</h5>
          <p>Some representative placeholder content for the second slide.</p>
        </div>
      </div>
      <div class="carousel-item">
        <img src="https://images.pexels.com/photos/1413412/pexels-photo-1413412.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" class="d-block w-100" alt="...">
        <div class="carousel-caption d-none d-md-block">
          <h5>Third slide label</h5>
          <p>Some representative placeholder content for the third slide.</p>
        </div>
      </div>
    </div>
    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev">
      <span class="carousel-control-prev-icon" aria-hidden="true"></span>
      <span class="visually-hidden">Previous</span>
    </button>
    <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next">
      <span class="carousel-control-next-icon" aria-hidden="true"></span>
      <span class="visually-hidden">Next</span>
    </button>
  </div>
```

## <!-- about.html -→

```html
<div>
    <h1>About Us</h1>
    <p>Learn more about our company...</p>
</div>
```

**Update the Main HTML File**: Use the `ng-view` directive to define where the routed views will be injected.

```html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
    <style>
        *, :root{
            font-size: large;
        }
    </style>
</head>
<body class="container">
    <section>
        <nav class="my-3 me-auto w-100 d-flex justify-content-between">
            <div class="text-start">
                Logo
            </div>
            <div class="text-end">
                <a href="#!/home">Home</a>
                <a href="#!/about">About</a>
            </div>
        </nav>
        <hr />
    </section>
    <section class="my-4" ng-view></section>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script type="text/javascript">
        var app = angular.module('myApp', ['ngRoute']);
        app.config(['$routeProvider', function($routeProvider) {
            $routeProvider
                .when('/home', {
                    templateUrl: '../home.html',
                    controller: 'HomeController'
                })
                .when('/about', {
                    templateUrl: '../about.html',
                    controller: 'AboutController'
                })
                .otherwise({
                    redirectTo: '/home'
                });
        }]);
        app.controller('HomeController', ['$scope', function($scope) {
            $scope.message = "Welcome to the Home Page";
        }]);

        app.controller('AboutController', ['$scope', function($scope) {
            $scope.message = "Learn more About Us";
        }]);

    </script>
</body>
</html>
```

#### Explanation of Key Concepts

- **ngRoute Module**: The module that provides routing and deep-linking services and directives.
- **$routeProvider**: The service used to configure routes, including the template to load and the controller to use.
- **ng-view Directive**: A directive that acts as a placeholder for the view specified in the routes. The view is loaded and compiled into the DOM when the route changes.

#### Route Configuration Methods

- **when(path, route)**: Maps a URL path to a route definition object that contains the template and controller.
- **otherwise(params)**: Defines a fallback route when no other routes match.

#### Example in Detail

In the configuration block:

- `.when('/home', { templateUrl: '../home.html', controller: 'HomeController' })`: Specifies that when the URL fragment is `#!/home`, the `home.html` template should be loaded and the `HomeController` should be used.
- `.when('/about', { templateUrl: '../about.html', controller: 'AboutController' })`: Specifies that when the URL fragment is `#!/about`, the `about.html` template should be loaded and the `AboutController` should be used.
- `.otherwise({ redirectTo: '/home' })`: Specifies that if the URL fragment does not match any defined routes, the application should redirect to `#!/home`.

#### Benefits of Using AngularJS Routing

- **Improved User Experience**: Enables seamless navigation between views without full page reloads.
- **Maintained State**: Keeps the application state consistent without losing data during navigation.
- **Clean URLs**: Supports clean and readable URLs which can be bookmarked and shared.

![How does routing work in AngularJS?](https://www.mindstick.com/mindstickforums/c68b6cc5-3cc8-4db1-bb73-60f7cf9abcfd/images/8d936ded-4ce2-4199-b207-10286de72236.png)


---

Original Source: https://www.mindstick.com/forum/160771/how-does-routing-work-in-angularjs

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
