Open In App

How to execute a routing in the AngularJS framework ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn about how we can perform routing in AngularJS, along with understanding its implementation through the code example.  

Routing in AngularJS helps to develop Single Page Applications, which is a web app that loads only a single page, and the part of the page instead of the entire page gets updated with every click of the mouse. As a consequence of this, the pages load faster ensuring high performance & efficient application. As the user interacts with the web app, pages are updated dynamically. The user can navigate through different pages with no page reloading. Since routing is done on the same HTML page, the user will experiences that they have not left the page. In AngularJS, routing allows creating the different URLs for different content in a web application with the help of the ngRoute module and $routeProvider.

The ng-route module is used to route to different pages in a Single Page Application, without reloading the pages. When the URL is specified, the routing engine captures the URL and renders the view according to the defined routing rules.  

The $routeProvider can be used to configure the routes and define what page will be displayed when the user clicks on a particular link. It accepts when() method that is used to specify the new route definition to the $route service or otherwise() method that is used to set the route definition to change the route when no route definition is matched.

Approach:

  • Add a reference to angular-route.js. This step is mandatory as this JavaScript file has all the main modules required for routing.

Syntax:

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

  • Create an application module and specify ngRoute as a dependency module, so that routing functionality can be used within the application.

Syntax:

var app = angular.module("myApp",['ngRoute']);
  • Configure $routeProvider to provide the routes in the application using the config() method. Use $routeProvider.when(path, route) method to configure routing rules. The first parameter is the request URL and the second parameter is the object containing properties like controller and template. Use the otherwise() method to redirect to the base URL if the user requests a URL that is different from the configured rules.

Syntax:

app.config(function ($routeProvider) {
  $routeProvider
    .when("/", {
      templateUrl: "home.html",
    })
    .when("/tutorials", {
      templateUrl: "tutorials.html",
      controller: "tutorialsController",
    })
    .when("/courses", {
      templateUrl: "courses.html",
      controller: "coursesController",
    })
    .when("/projectideas", {
      templateUrl: "projectideas.html",
      controller: "projectideasController",
    })
    .otherwise({ redirectTo: "/" });
});
  • Define links to the routes within the HTML page.

Syntax:

<a href="#/tutorials">Tutorials</a>
  • Include the ng-view directive inside a div tag within the HTML page to display the content of the route chosen.

Example: In this example, there are 4 pages to route, namely:

  • Home page
  • Tutorials page
  • Courses page
  • Project Ideas page

While the user navigates through these pages using the navigation bar, we will ensure the page will not reload. Instead, the contents of the selected page are displayed on the same page.

example1.html:

This is the main page of the application. In the script tag, a reference to angular-route.min.js has been added. This file has the HTML elements like the heading “GeeksforGeeks” and the navbar. In the navbar, links to the routes have been specified. It also has a div tag where the ng-view directive has been specified so that when the user selects a page the contents of that particular page can be displayed. In the script tag, a reference to the javascript.js file has also been added. 

HTML




<!DOCTYPE html>
<html ng-app="myApp">
 
<head>
    <title>Routing in AngularJS</title>
    <script src=
    </script>
    <script src=
    </script>
    <style>
        a {
            font-size: 25px;
            color: black;
            text-decoration: none;
            padding-right: 20px;
            padding-left: 20px;
        }
         
        nav {
            background-color: #d0dbd4;
        }
         
        h1 {
            color: #39ad64;
        }
    </style>
</head>
 
<body>
    <nav>
        <a id="active1" href="#/">Home</a>
        <a id="active2" href="#/tutorials">Tutorials</a>
        <a id="active3" href="#/courses">Courses</a>
        <a id="active4" href="#/projectideas">Project Ideas</a>
    </nav>
    <h1>GeeksforGeeks</h1>
    <div ng-view></div>
    <script type="text/javascript" src="javascript.js"></script>
</body>
</html>


javascript.js:

This javascript file contains the module named “myApp” which is created where the ngRoute module has been specified as a dependency module. Using the config() method, the $routeProvider module has been configured and routes in the application have been provided. For each route, its URL and controller to be used is specified. 

Javascript




<script>
  var app = angular.module("myApp", ["ngRoute"]);
  app.config(function ($routeProvider) {
    $routeProvider
      .when("/", {
        templateUrl: "home.html",
      })
      .when("/tutorials", {
        templateUrl: "tutorials.html",
        controller: "tutorialsController",
      })
      .when("/courses", {
        templateUrl: "courses.html",
        controller: "coursesController",
      })
      .when("/projectideas", {
        templateUrl: "projectideas.html",
        controller: "projectideasController",
      })
      .otherwise({ redirectTo: "/" });
  });
  app.controller("tutorialsController", function ($scope) {
    $scope.tutorials = [
      "Practice DS and Algo.",
      "Algorithms",
      "Data Structure",
      "Software Designs",
      "CS Subjects",
    ];
  });
  app.controller("coursesController", function ($scope) {
    $scope.courses =
    ["Live Courses",
     "Self-Paced Courses",
     "School Courses"];
  });
  app.controller("projectideasController", function ($scope) {
    $scope.c = [
      "Program for face detection",
      "Program for coin detection",
      "Program to blur an image",
      "Program to create a single colored blank image",
    ];
    $scope.java = [
      "A Group chat Application",
      "Generating Password and OTP in Java",
      "Creative Programming in Processing",
    ];
    $scope.python = [
      "Make a Notpad using Tkinter",
      "Color Game using Tkinter in Python",
      "Message Encode-Decode using Tkinter",
      "Twitter sentiment analysis using Python",
    ];
 
    $scope.projectideas = [
      { course: "C++", projects: $scope.c },
      { course: "Java", projects: $scope.java },
      { course: "Python", projects: $scope.python },
    ];
  });
</script>


home.html: This page is used to display the different options available on the home page.

HTML




<style>
#active1 {
    background-color: #39ad64;
}
</style>
<h1>Write</h1>
 
<p>Write articles and get featured</p>
 
<h1>Practice</h1>
 
<p>Learn and code with the best industry experts</p>
 
<h1>Premium</h1>
 
<p>Get access to ad-free content, doubt assistance and more</p>


tutorials.html: The ng-repeat directive is used to create a list of the tutorials available. Here, the names of the tutorials are taken from the JavaScript array “tutorials”. This array has been defined in the tutorialsController in the javascript.js file.

HTML




<style type="text/css">
    #active2 {
        background-color: #39ad64;
    }
</style>
<h2>Tutorials</h2>
<ul ng-repeat="x in tutorials">
    <li>{{x}}</li>
</ul>


courses.html: This page is similar to the tutorials page. Here, the ng-repeat directive is used to create a list of the courses. The names of the courses have been taken from the JavaScript array named “courses” in the coursesController defined in the javascript.js file.

HTML




<style type="text/css">
    #active3 {
        background-color: #39ad64;
    }
</style>
<h2>Courses</h2>
<ul ng-repeat="x in courses">
    <li>{{x}}</li>
</ul>


projectideas.html: In this file, we have used the ng-repeat directive to make the list of project ideas. The names of the projects have been taken from the arrays defined in the projectideasController in the javascript.js file.

HTML




<style type="text/css">
    #active4 {
        background-color: #39ad64;
    }
</style>
<h2>Project Ideas</h2>
<ul ng-repeat="x in projectideas">
    <li>{{x.course}}</li>
    <ul ng-repeat="y in x.projects">
        <li>{{y}}</li>
    </ul>
</ul>


Note: To run these files, save these files with the same filenames, as mentioned, and run the main file i.e. example1.html on a live server or on a local server.

Output:

 Routing in AngularJS 

Explanation: The user can navigate through different pages using the navbar. As we can see in the output, the page is not reloading, instead all the pages ie., home, tutorials, courses, and project ideas, are being displayed on the same HTML page. The navbar and the heading do not change. The content of the different web pages is displayed in the <div> tag where the ng-view directive was used in the example1.html file. This is how a single-page application works.

Note: When the user loads the page, it loads the home page because of the “otherwise” option in the $routeProvider function.



Last Updated : 05 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads