blog

Home / DeveloperSection / Blogs / Explain Routing in AngularJS

Explain Routing in AngularJS

Explain Routing in AngularJS

Ashutosh Kumar Verma 65 21-Jun-2024

Angularjs Routing

In AngularJS, routing refers to a tool that allows you to define navigation paths in 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 ($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

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, 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, 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 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

 

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 While AngularJS primarily targets SPAs, server-side techniques or Angular Universal can be used for SEO 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)

<!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

<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

<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

<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

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

Routing in AngularJS simplifies navigation and view management in single-page applications, allowing developers to create a structured and responsive user experience through routing, view templates, and controller logic

 

Also, Read: Custom Filters in AngularJS


Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By