![]() |
VOOZH | about |
In this article, we will see the role of the $routeProvider in AngularJS, along with understanding the basic implementation through the examples. Routing allows us to create Single Page Applications. To do this, we use ng-view and ng-template directives, and $routeProvider services. We use $routeProvider to configure the routes. The config() takes a function that takes the $routeProvider as a parameter and the routing configuration goes inside the function. The $routeProvider is a simple API that accepts either when() or otherwise() method. We need to install the ngRoute module.
Example 1: This example describes the basic usage of the $routeProvider in AngularJS.
Explanation: $routeProvider is a function under config (mainApp module) using the key as '$routeProvider'. $routeProvider.when defines the URL "/addStudent". The default view is set by "otherwise". "controller" is used for the view.
Output: From the output, notice the URL & the content that changes while clicking on the given links:
How To Configure The $routeprovider?
The $routeProvider creates the $route service. By configuring the $routeProvider before the $route service we can set routes in HTML templates which will be displayed. The $routeProvider is configured with the help of calls to the when() and otherwise() functions.
Syntax to configure the routes in AngularJS:
var app = angular.module("appName", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.when('/1stview', {
templateUrl: '1stview.html',
controller: 'Controller1'
}).when('/view2', {
templateUrl: '2ndview.html',
controller: 'Controller2'
}).otherwise({
redirectTo: '/1stview'
});
}); Here, Path is the URL after the hash(#) symbol.
The route contains two properties:
Example 2: In this example, the $routeProvider is used to define the page when the user clicks the link.
Output: From the output, notice the URL that changes while clicking on the given links: