Effective Routing in AngularJS: A Comprehensive Example with ngRoute and $routeProvider

Explore the power of AngularJS routing with ngRoute and $routeProvider in our blog post. Learn how to create complex single-page applications using this powerful feature, providing seamless navigation and interaction. Dive into practical examples and a step-by-step guide to implementing it into your own projects.

Introduction

AngularJS provides mechanisms for routing in web applications with the ngRoute module and the $routeProvider. Defined routing allows different contents to be loaded and displayed based on the URL without reloading the page.

Using ngRoute

The ngRoute module of AngularJS provides routing services and directives. To utilize the routing feature, the angular-route.js script must be downloaded, which contains the ngRoute module. Alternatively, the module can also be included via CDN.

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

Configuring $routeProvider

The $routeProvider is used to configure routes. The config() function configures the $routeProvider by defining routes that respond to specific URLs. The $routeProvider offers a simple API that accepts either the when() or otherwise() method.

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

    mainApp.config(function($routeProvider) {
      $routeProvider
        .when('/home', {
          templateUrl: 'home.html',
          controller: 'StudentController'
        })
        .when('/viewStudents', {
          templateUrl: 'viewStudents.html',
          controller: 'StudentController'
        })
        .otherwise({
          redirectTo: '/home'
        });
    });

Example Application

To demonstrate routing in AngularJS, we’ll create a simple application with two views: a home page and a page to display student information.

 
    mainApp.controller('StudentController', function($scope) {
      $scope.students = [
        {name: 'Mark Waugh', city:'New York'},
        {name: 'Steve Jonathan', city:'London'},
        {name: 'John Marcus', city:'Paris'}
      ];

      $scope.message = "Click on the hyperlink to view the students list.";
    });

Conclusion

By using AngularJS routing, complex single-page applications can be created, offering user-friendly navigation and interaction without page reloads. AngularJS routing enables you to build effective single-page applications and enhance user experience. It’s a powerful tool for structuring and organizing complex applications. If you want to learn more about AngularJS, explore our online demo and delve deeper into the world of AngularJS routing!

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: