Before we start with routing, let's just have a quick overview on Single-Page Applications.
Single page applications or (SPAs) are web applications that load a single HTML page and dynamically update the page based on the user interaction with the web application.
In AngularJS, routing is what allows you to create Single Page Applications.
Let's take an example of a site which is hosted via the URL http://example.com/index.html.
On this page, you would host the main page of your application. Suppose if the application was organizing an Event and one wanted to see what the various events on display are, or wanted to see the details of a particular event or delete an event. In a Single Page application, when routing is enabled, all of this functionality would be available via the following links
http://example.com/index.html#ShowEvent
http://example.com/index.html#DisplayEvent
http://example.com/index.html#DeleteEvent
The # symbol would be used along with the different routes (ShowEvent, DisplayEvent, and DeleteEvent).
Note that the main URL stays the same.
In this tutorial, you will learn-
So as we discussed earlier, routes in AngularJS are used to route the user to a different view of your application. And this routing is done on the same HTML page so that the user has the experience that he has not left the page.
In order to implement routing the following main steps have to be implemented in your application in any specific order.
The next important step is to add a dependency to the ngRoute module from within your application. This dependency is required so that routing functionality can be used within the application. If this dependency is not added, then one will not be able to use routing within the angular.JS application.
Below is the general syntax of this statement. This is just a normal declaration of a module with the inclusion of the ngRoute keyword.
var module = angular.module("sampleApp", ['ngRoute']);
Below is the general syntax of this statement which is very self-explanatory. It just states that when the relevant path is chosen, use the route to display the given view to the user.
when(path, route)
<a href="#/route1">Route 1</a><br/>
Now, let's look at an example of routing using the above-mentioned steps.
In our example,
We will present 2 links to the user,
Step 1) Include the angular-route file as a script reference.
This route file is necessary in order to make use of the functionalities of having multiple routes and views. This file can be downloaded from the angular.JS website.
Step 2) Add href tags which will represent links to "Angular JS Topics" and "Node JS Topics."
Step3) Add a div tag with the ng-view directive which will represent the view.
This will allow the corresponding view to be injected whenever the user clicks on either the "Angular JS Topics" or "Node JS Topics."
Step 4) In your script tag for AngularJS, add the "ngRoute module" and the "$routeProvider" service.
Code Explanation:
Step 5) Next is to add controllers to process the business logic for both the AngularController and NodeController.
In each controller, we are creating an array of key-values pairs to store the Topic names and descriptions for each course. The array variable 'tutorial' is added to the scope object for each controller.
<!DOCTYPE html> <html> <head> <meta chrset="UTF 8"> </head> <body ng-app="sampleApp"> <title>Event Registration</title> <script src="https://code.angularjs.org/1.6.9/angular-route.js"></script> <script src="https://code.angularjs.org/1.6.9/angular.min.js"></script> <script src="https://code.angularjs.org/1.6.9/angular.js"></script> <h1> Guru99 Global Event</h1> <div class="container"> <ul> <li><a href="#Angular">Angular JS Topics</a></li> <li><a href="#Node.html">Node JS Topics</a></li> </ul> <div ng-view></div> </div> <script> var sampleApp = angular.module('sampleApp',['ngRoute']); sampleApp.config(['$routeProvider', function($routeProvider){ $routeProvider. when('/Angular',{ templateUrl : '/Angular.html', controller: 'AngularController' }). when("/Node", { templateUrl: '/Node.html', controller: 'NodeController' }); }]); sampleApp.controller('AngularController',function($scope) { $scope.tutorial = [ {Name:"Controllers",Description :"Controllers in action"}, {Name:"Models",Description :"Models and binding data"}, {Name:"Directives",Description :"Flexibility of Directives"} ] }); sampleApp.controller('NodeController',function($scope){ $scope.tutorial = [ {Name:"Promises",Description :"Power of Promises"}, {Name:"Event",Description :"Event of Node.js"}, {Name:"Modules",Description :"Modules in Node.js"} ] }); </script> </body> </html>
Step 6) Create pages called Angular.html and Node.html. For each page we are carrying out the below steps.
These steps will ensure that all of the key-value pairs of the array are displayed on each page.
<h2>Anguler</h2> <ul ng-repeat="ptutor in tutorial"> <li>Course : {{ptutor.Name}} - {{ptutor.Description}}</li> </ul>
<h2>Node</h2> <ul ng-repeat="ptutor in tutorial"> <li>Course : {{ptutor.Name}} - {{ptutor.Description}}</li> </ul>
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
If you click on the AngularJS Topics link the below output will be displayed.
The output clearly shows that,
Routing in AngularJS also provides the facility to have a default route. This is the route which is chosen if there is no match for the existing route.
The default route is created by adding the following condition when defining the $routeProvider service.
The below syntax just simply means to redirect to a different page if any of the existing routes don't match.
otherwise ({ redirectTo: 'page' });
Let's use the same example above and add a default route to our $routeProvider service.
function($routeProvider){ $routeProvider. when('/Angular',{ templateUrl : 'Angular.html', controller: 'AngularController' }). when("/Node", { templateUrl: 'Node.html', controller: 'NodeController' }). otherwise({ redirectTo:'/Angular' }); }]);
Code Explanation:
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
From the output,
Angular also provides the functionality to provide parameters during routing. The parameters are added to the end of the route in the URL, for example, http://guru99/index.html#/Angular/1. In this example
The syntax of how parameters look in the URL is shown below:
HTMLPage#/route/parameter
Here you will notice that the parameter is passed after the route in the URL.
So in our example, above for the Angular JS topics, we can pass a parameter's as shown below
Sample.html#/Angular/1
Sample.html#/Angular/2
Sample.html#/Angular/3
Here the parameters of 1, 2 and 3 can actually represent the topicid.
Let's look in detail at how we can implement this.
Step 1) Add the following code to your view
Add a table to show all the topics for the Angular JS course to the user
Add a table row for showing the topic "Controllers." For this row, change the href tag to "Angular/1" which means that when the user clicks this topic, the parameter 1 will be passed in the URL along with the route.
Add a table row for showing the topic "Models." For this row, change the href tag to "Angular/2" which means that when the user clicks this topic, the parameter 2 will be passed in the URL along with the route.
Add a table row for showing the topic "Directives." For this row, change the href tag to "Angular/3" which means that when the user clicks this topic, the parameter 3 will be passed in the URL along with the route.
Step 2) In the routeprovider service function add the:topicId to denote that any parameter passed in the URL after the route should be assigned to the variable topicId.
Step 3) Add the necessary code to the controller
<!DOCTYPE html> <html> <head> <meta chrset="UTF 8"> <title>Event Registration</title> </head> <body ng-app="sampleApp"> <script src="https://code.angularjs.org/1.6.9/angular-route.js"></script> <script src="https://code.angularjs.org/1.6.9/angular.min.js"></script> <script src="/lib/bootstrap.js"></script> <script src="/lib/bootstrap.css"></script> <h1> Guru99 Global Event</h1> <table class="table table-striped"> <thead> <tr> <th>#</th><th>Angular JS topic</th><th>Description</th><th></th> </tr> </thead> <tbody> <tr> <td>l</td><td>l</td><td>Controllers</td> <td><a href="#Angular/l">Topic details</a></td> </tr> <tr> <td>2</td><td>2</td><td>Models</td> <td><a href="#Angular/2">Topic details</a></td> </tr> <tr> <td>3</td><td>3</td><td>Directives</td> <td><a href="#Angular/3">Topic details</a></td> </tr> </tbody> </table> <script> var sampleApp = angular.module('sampleApp',['ngRoute']); sampleApp.config( function($routeProvider){ $routeProvider. when('/Angular/:topicId',{ templateUrl : 'Angular.html', controller: 'AngularController' }) }); sampleApp.controller('AngularController',function($scope,$routeParams) { $scope.tutorialid=$routeParams.topicId }); </script> </body> </html>
Step 4) Add the expression to display the tutorialid variable in the Angular.html page.
<h2>Anguler</h2> <br><br>{{tutorialid}}
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
In the output screen,
The $route service allows you to access the properties of the route. The $route service is available as a parameter when the function is defined in the controller. The general syntax of how the $route parameter is available from the controller is shown below;
myApp.controller('MyController',function($scope,$route)
Let's have a look on how we can use the $route service.
In this example,
So, let's see the steps which we need to carry out to achieve this.
Step 1) Add a custom key-value pair to the route. Here, we are adding a key called 'mytext' and assigning it a value of "This is angular."
Step 2) Add the relevant code to the controller
<!DOCTYPE html> <html> <head> <meta chrset="UTF 8"> <title>Event Registration</title> </head> <body ng-app="sampleApp"> <script src="https://code.angularjs.org/1.6.9/angular-route.js"></script> <script src="https://code.angularjs.org/1.6.9/angular.min.js"></script> <script src="/lib/bootstrap.js"></script> <script src="/lib/bootstrap.css"></script> <h1> Guru99 Global Event</h1> <table class="table table-striped"> <thead> <tr> <th>#</th><th>Angular JS topic</th><th>Description</th><th></th> </tr> </thead> <tbody> <tr> <td>l</td><td>l</td><td>Controllers</td> <td><a href="#Angular/l">Topic details</a></td> </tr> <tr> <td>2</td><td>2</td><td>Models</td> <td><a href="#Angular/2">Topic details</a></td> </tr> <tr> <td>3</td><td>3</td><td>Directives</td> <td><a href="#Angular/3">Topic details</a></td> </tr> </tbody> </table> <script> var sampleApp = angular.module('sampleApp',['ngRoute']); sampleApp.config(['$routeProvider', function($routeProvider){ $routeProvider. when('/Angular/:topicId',{ mytext:"This is angular", templateUrl : 'Angular.html', controller: 'AngularController' }) }]); sampleApp.controller('AngularController',function($scope,$routeParams,$route) { $scope.tutorialid=$routeParams.topicId; $scope.text=$route.current.mytext; }); </script> </body> </html>
Step 3) Add a reference to the text variable from the scope object as an expression. This will be added to our Angular.html page as shown below.
This will cause the text "This is angular" to be injected into the view. The {{tutorialid}} expression is the same as that seen in the previous topic and this will display the number '1'.
<h2>Anguler</h2> <br><br>{{text}} <br><br>
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
From the output,
HTML5 routing is used basically to create clean URL. It means the removal of the hashtag from the URL. So the routing URLs, when HTML5 routing is used, would appear as shown below
Sample.html/Angular/1
Sample.html/Angular/2
Sample.html/Angular/3
This concept is normally known as presenting pretty URL to the user.
There are 2 main steps which need to be carried out for HTML5 routing.
Let's look into the detail of how to carry out the above-mentioned steps in our example above
Step 1) Add the relevant code to the angular module
Step 2) Remove all the #tags for the links ('Angular/1', 'Angular/2', 'Angular/3') to create easy to read URL.
<!DOCTYPE html> <html> <head> <meta chrset="UTF 8"> <title>Event Registration</title> </head> <body ng-app="sampleApp"> <script src="https://code.angularjs.org/1.6.9/angular-route.js"></script> <script src="https://code.angularjs.org/1.6.9/angular.min.js"></script> <script src="/lib/bootstrap.js"></script> <script src="/lib/bootstrap.css"></script> <h1> Guru99 Global Event</h1> <table class="table table-striped"> <thead> <tr> <th>#</th><th>Angular JS topic</th><th>Description</th><th></th> </tr> </thead> <tbody> <tr> <td>l</td><td>l</td><td>Controllers</td> <td><a href="/Angular/l">Topic details</a></td> </tr> <tr> <td>2</td><td>2</td><td>Models</td> <td><a href="/Angular/2">Topic details</a></td> </tr> <tr> <td>3</td><td>3</td><td>Directives</td> <td><a href="/Angular/3">Topic details</a></td> </tr> </tbody> </table> <script> var sampleApp = angular.module('sampleApp',['ngRoute']); sampleApp.constant("baseUrl","http://localhost:63342/untitled/Sample.html/Angular"); sampleApp.config( function($routeProvider,$locationProvider){ $routeProvider. when('/Angular/:topicId',{ templateUrl : 'Angular.html', controller: 'AngularController' }) }); sampleApp.controller('AngularController',function($scope,$routeParams,$route) { $scope.tutorialid=$routeParams.topicId }); </script> </body> </html>
If the code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:
From the output,
Summary