Introduction of Routing in AJS
- The concept of Routing in AJS is done using
ngRoute
module helps us to navigate to different pages in our application, but remaining with SPA (Single Page Application), with no more page reloading.
Definition
- Routing in AngularJS is a crucial feature that allows developers to create single-page applications (SPAs) with multiple views without requiring a full page reload.
- AngularJS routing provides a powerful way to manage navigation within single-page applications, allowing for a seamless user experience. By leveraging the
$routeProvider
service and thengView
directive, developers can define routes, load views, and control application state effectively.
Characteristics
- AngularJS provides a routing mechanism using the
$routeProvider
service, which is part of thengRoute
module. ThengRoute
module helps in navigating the application to different pages (when required) without reloading the entire application called Routing i.e. it helps our application to become a ‘Single-Page Application(SPA)’. - For Routing in Angular JS –
- ngRoute Module: This module provides routing and deep linking services and directives for AngularJS applications.
- $routeProvider Service: Configures routes and maps URLs to specific views and controllers.
- ngView Directive: The directive used to display the view in the specified layout.
Requirements
- The AngularJS Route module (
ngRoute)
is must added as a dependency in the array parameter of a module for routing (such as … [“ngRoute”]). - The AngularJS library is also required for routing applications –
<script src=”https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js”></script>
$routeProvider
:- It is used to configure different required routes using different methods in the application.
- with this,
$routeProvider
we can define what page to display when a user clicks a link. - The
config
method ofrouteProvider
is used to perform activities when the application is loading. - The
when
method of$routeProvider
is used as a conditional statement andotherwise
the method as a default switch case. - With the
$routeProvider
we can also define a controller for each “view” in the application as needed.
- Define the controllers for each route
app.controller(‘HomeController’, function($scope) { $scope.message = ‘Welcome to the Home Page!’; });
app.controller(‘AboutController’, function($scope) { $scope.message = ‘Learn more About Us!’; });
app.controller(‘ContactController’, function($scope) { $scope.message = ‘Contact Us here!’; });
- Also,
ng-view
directive is used as a container to store/put the output content provided by the routing, in three ways – <div ng-view></div>, <ng-view></ng-view> and <div class=”ng-view”></div>, but an application can only have oneng-view
directive, and this will be the placeholder for all views provided during the routing.
Advantages
- Routing makes the application faster by loading the minimum number of pages.
Routing Program Examples
0 Comments