Open In App

What is the Difference Between $routeProvider and $stateProvider in AngularJS ?

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In AngularJS, as we create Single-Page Applications, we need to implement the routing of components to view those images without having full page reloads. This can be achieved with the most popular routing methods, i.e., $routeProvider (ngRoute) and $stateProvider (ui-router).

In this article, we will explore the $routeProvider and $stateProvider in AngularJS and understand their basic implementation with the help of examples, along with knowing the difference between these two methods

$routeProvider

The $routeProvider is part of the ngRoute module, which is an official AngularJS module used for basic routing in AngularJS applications. It provides a simple and straightforward way to define routes using a configuration object. With $routeProvider, we can specify the URL pattern and associate it with a template and controller, making it a suitable choice for small to medium-sized projects with relatively simple routing requirements.

Syntax

var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
    $routeProvider
        .when('/routePath', {
            templateUrl: 'template.html',
            controller: 'ControllerName'
        })
        .otherwise({
            redirectTo: '/defaultPath'
        });
});

Example: The below example demonstrates the usage of $routeProvider in AngularJS. Here, when the user clicks on the NavBar links, the application renders the associated route page and displays the content accordingly.

index.html




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <base href="/">
    <script src=
      </script>
    <script src=
      </script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
  
        nav {
            background-color: #333;
        }
  
        ul {
            list-style: none;
            margin: 0;
            padding: 0;
        }
  
        li {
            display: inline;
            margin-right: 20px;
        }
  
        li a {
            text-decoration: none;
            color: #fff;
            font-weight: bold;
            font-size: 18px;
        }
  
        .container {
            text-align: center;
            margin-top: 20px;
        }
  
        h1 {
            color: #4CAF50;
            font-size: 36px;
        }
  
        h3 {
            color: #333;
            font-size: 24px;
        }
    </style>
</head>
  
<body>
    <nav>
        <ul>
            <li><a href="#!/">Home</a></li>
            <li><a href="#!/about">About</a></li>
        </ul>
    </nav>
    <div ng-view class="container">
    </div>
  
    <script>
        var app = angular.module("myApp", ["ngRoute"]);
        app.config(function ($routeProvider) {
            $routeProvider
                .when("/", {
                    templateUrl: "home.html",
                })
                .when("/about", {
                    templateUrl: "about.html",
                })
                .otherwise({
                    redirectTo: "/"
                });
        });
    </script>
</body>
  
</html>


home.html




<div class="container">
    <h1>GeeksforGeeks</h1>
    <h3>$routeProvider Example</h3>
    <p>
        GeeksforGeeks is a technology education
        platform offering a wide range of 
        tutorials and articles on various
        programming topics.
    </p>
</div>


about.html




<div class="container">
    <h1>About GeeksforGeeks</h1>
    <p>
        GeeksforGeeks is a computer science 
        portal and is known for its quality 
        content and problem-solving expertise.
        We cover a variety of programming 
        languages, data structures, algorithms,
        and more.
    </p>
    <img src=
         alt="GeeksforGeeks Logo"
         width="300" 
         height="300" />
</div>


Output

Ex

$stateProvider

The $stateProvider is part of the ui-router library, which offers more advanced routing features compared to ngRoute. It allows for complex and nested routing configurations, enabling the creation of State-Based Routing Hierarchies. This is particularly useful for large and complex applications where routes can have multiple views and states. The $stateProvider provides a powerful and flexible way to manage different states of your application, making it a better choice when you need more advanced routing capabilities and state management.

Syntax

var app = angular.module('myApp', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/defaultPath');
    $stateProvider
        .state('stateName', {
            url: '/statePath',
            templateUrl: 'template.html',
            controller: 'ControllerName'
        });
});

Example: The below example demonstrates the usage of $stateProvider in AngularJS. Here, we have defined three states (‘dsa’, ‘fullstack’, and ‘ai’) and display content for each state in a <div ui-view> element when the user clicks on the respective images.

index.html




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <base href="/">
    <script src=
      </script>
    <script src=
      </script>
</head>
  
<body>
    <header style="background-color: #ffffff;
                   text-align: center; 
                   padding: 20px 0;">
        <h1 style="color: green;
                   font-size: 40px; 
                   margin: 0;">
              Welcome to GeeksforGeeks
          </h1>
        <h3 style="color: rgb(0, 0, 0); 
                   font-size: 34px;">
              $stateProvider Example
          </h3>
    </header>
    <nav style="text-align: center;">
        <div class="image-link" ui-sref="dsa"
            style="display: inline-block; 
                   margin: 20px; 
                   cursor: pointer; 
                   background-color: #fff;
                   border-radius: 10px; 
                   transition: transform 0.2s;">
            <img src=
                 alt="DSA" 
                 style="width: 300px; 
                        height: 200px; 
                        border: 3px solid #4CAF50;
                        border-radius: 10px;">
            <p style="color: rgb(0, 0, 0); 
                      font-size: 20px; 
                      padding: 10px;">
                  Data Structures and Algorithms
              </p>
        </div>
        <div class="image-link"
             ui-sref="fullstack"
             style="display: inline-block;
                    margin: 20px; 
                    cursor: pointer; 
                    background-color: #fff;  
                    border-radius: 10px; 
                    transition: transform 0.2s;">
            <img src=
                 alt="Full Stack" 
                 style="width: 300px; height: 
                        200px; border: 3px solid #4CAF50;
                        border-radius: 10px;">
            <p style="color: rgb(0, 0, 0);
                      font-size: 20px; 
                      padding: 10px;">
                  Full Stack Development
              </p>
        </div>
        <div class="image-link"
             ui-sref="ai"
             style="display: inline-block;
                    margin: 20px;
                    cursor: pointer; 
                    background-color: #fff;
                    border-radius: 10px; 
                    transition: transform 0.2s;">
            <img src=
                 alt="AI" 
                 style="width: 300px; 
                        height: 200px;
                        border: 3px solid #4CAF50;
                        border-radius: 10px;">
            <p style="color: rgb(0, 0, 0); 
                      font-size: 20px; 
                      padding: 10px;">
                  Artificial Intelligence
              </p>
        </div>
    </nav>
  
    <div ui-view class="content"
        style="background-color: rgb(147, 251, 152); 
               padding: 20px; 
               border-radius: 10px; 
               box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);">
    </div>
  
    <script>
        var app = angular.module("myApp", ["ui.router"]);
        app.config(function ($stateProvider, $urlRouterProvider) {
            $urlRouterProvider.otherwise('/');
            $stateProvider
                .state('dsa', {
                    url: '/dsa',
                    template:
            '<h1>Data Structures and Algorithms</h1>'+
            '<p>This program is designed to take you'+
            ' on a transformative journey from mastering'+
            ' Data Structures and Algorithms (DSA) to '+
            'becoming a proficient developer. Whether'+
            'you aspire to become a full-stack developer'+
            ' or specialize in a specific technology stack, '+
            'this program provides the essential building '+
            'blocks for your coding journey starting right'+
            ' from basic programming to building applications.</p>'
                })
                .state('fullstack', {
                    url: '/fullstack',
                    template:
            '<h1>Full Stack Development</h1>'+
            '<p>Looking to become a full-stack developer?;'+
            ' This live, online course with a focus on the '+
            'popular JS library React for front-end and Node.js'+
            ' for back-end along with APIs and deployment is'+
            ' a must-have program for any aspiring developer.</p>'
                })
                .state('ai', {
                    url: '/ai',
                    template: 
            '<h1>Artificial Intelligence</h1>'+
            '<p>Unlock success with our GATE Data Science'+
            ' and Artificial Intelligence 2024. Specially '+
            'curated by experts, our courses in Machine Learning'+
            ' and Artificial Intelligence are your gateway to'+
            ' academic excellence. Fast-track your career and '+
            'unleash your potential - Enroll now!</p>'
                });
        });
    </script>
</body>
  
</html>


Output:

Ex2

Difference between $routeProvider and $stateProvider

Basis

$routeProvider

$stateProvider

AngularJS Module Dependency

This method implements the ngRoute as a dependency. 

This method implements the ui.router as a dependency.

URL Path

URL path is set directly in the when method.

URL path is set using the URL property within the state method.

Template URL

templateUrl property specifies the HTML template for the route.

template property specifies the HTML template for the state.

Controller

controller property specifies the controller for the route.

controller property specifies the controller for the state.

Nested Views and States

Not natively supported.

Fully supports nested views and states for complex applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads