Conditional Routing In AngularJS

Introduction

You might be familiar with AngularJS Routing, and might have used it as well, but what if that routing needs to be applied on fulfillment of certain conditions? For those cases this article will help you.

To explain the conditional routing I am creatinghave created a sample application.

You might have read my previous article i.e. MVC Routing with Angular Routing. The application which was created in that article is also used here, I am just modifying it to my needs.

Step 1:

Firstly, I created a new View which will be used as a login page.

On this page I created two textboxes and a button, which will help to identify user authenticity. Apart from that I have created a div in which some message is written for non-authentic and non-authorized users, and one more div where some links and a container div is created.

  1. <!DOCTYPE html>  
  2. <html ng-app="angualarModule">  
  3. <head>  
  4.     <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.min.js"></script>  
  5.     <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.min.js"></script>  
  6.     <script src="~/Scripts/AngularController.js"></script>  
  7. </head>  
  8. <body>  
  9.     <form ng-controller="indexController">  
  10.         <div>  
  11.             <fieldset>  
  12.                 <legend>Login Demo</legend>  
  13.                 User Name:   
  14.                 <input type="text" ng-model="authentic.name" />  
  15.                 <br />  
  16.                 Password:   
  17.                 <input type="password" ng-model="authentic.pwd" />  
  18.                 <br />  
  19.                 <br />  
  20.                 <input type="button" value="Submit" ng-click="CheckUser(authentic)" />  
  21.             </fieldset>  
  22.         </div>  
  23.         <div ng-hide="AuthenticUser()">  
  24.             <a href="/#/firstPage">Call First Page</a>  
  25.             <br />  
  26.             <a href="/#/secondPage">Call Second Page</a>  
  27.             <div ng-view></div>  
  28.         </div>  
  29.         <div ng-hide="CheckNotaValidUser()">  
  30.             <h2>You are not an authorized user</h2>  
  31.         </div>  
  32.     </form>  
  33. </body>  
  34. </html>  

Step 2:

After this I worked on the Angular part, I created a new controller, where first of all a click function is created. In that function the models value is coming in "authentic" object.

  1. var angualarModule = angular.module("angualarModule", ['ngRoute']);  
  2. angualarModule.controller("indexController"function ($scope, $rootScope) 
  3. {  
  4.     $scope.CheckUser = function (authentic)
  5.     {  
  6.         if (authentic.name == "Anubhav" && authentic.pwd == "Chaudhary")
  7.        {  
  8.             $rootScope.validUser = true;  
  9.             $rootScope.userType = "Admin";  
  10.             $rootScope.NotaValidUser = false;  
  11.         }  
  12.         else if (authentic.name == "Mohit" && authentic.pwd == "Chaudhary"
  13.         {  
  14.             $rootScope.validUser = true;  
  15.             $rootScope.userType = "Normal";  
  16.         }  
  17.         else 
  18.         {  
  19.             $rootScope.validUser = false;  
  20.             $rootScope.NotaValidUser = true;  
  21.         }  
  22.     };  

According to the values entered in textboxes, some decisions are made, and accordingly some values are provided to $rootScope objects, which will help us while creating conditional routing.

You can see that the two divs which are created after the login div shown hide on a conditional basis, and for that, I have put functions in them which will provide them boolean value, and according to those values, these divs will be shown or hide. So, let's create these two functions; these will be created in the same Controller wherethe click function was created.

  1. $scope.CheckNotaValidUser = function ()
  2.    {  
  3.     if ($rootScope.NotaValidUser != undefined) 
  4.       {  
  5.         if ($rootScope.NotaValidUser == true
  6.         {  
  7.             return false;  
  8.         }  
  9.         else 
  10.         {  
  11.             return true;  
  12.         }  
  13.     }  
  14.     else
  15.      {  
  16.         return true;  
  17.     }  
  18. }  
  19. $scope.AuthenticUser = function () 
  20. {  
  21.     if ($rootScope.validUser == true
  22.     {  
  23.         return false;  
  24.     }  
  25.     else 
  26.    {  
  27.         return true;  
  28.     }  
  29. };  

Step 3: Now let's create routing, which will work on the click of hyperlinks available in third div.

  1. angualarModule.config(function ($routeProvider)
  2.  {  
  3.     $routeProvider.  
  4.     when('/firstPage'
  5.    {  
  6.         templateUrl: 'routedemo/first',  
  7.         controller: 'routeDemoFirstController'  
  8.     }).  
  9.     when('/secondPage'
  10.    {  
  11.         templateUrl: 'routedemo/second',  
  12.         controller: 'routeDemoSecondController'  
  13.     })  
  14. })  
  15. angualarModule.controller("routeDemoFirstController"function ($scope) 
  16. {  
  17.     $scope.FirstName = "Anubhav";  
  18.     $scope.LastName = "Chaudhary";  
  19. })  
  20. angualarModule.controller("routeDemoSecondController"function ($scope) 
  21. {  
  22.     $scope.MobileNumber = "123456";  
  23.     $scope.EmailID = "[email protected]";  
  24. })  

Step 4:

Now comes the main part, i.e., placing the condition for routing. For this I have used "$locationChangeStart" of Angular. This function will hit as soon as user clicks on any hyperlink or goes to some other page. It will work prior to anything else, so here we can check whether the user is authentic/authorized or not to see some values or to visit some page. If he's not, then we can redirect him to some other page, or we can show him some message, or we can also just let him stay on the current page.

  1. angualarModule.run(function ($rootScope, $location)
  2.  {  
  3.     $rootScope.$on("$locationChangeStart"function (event, next, current) 
  4.       {  
  5.         if ($rootScope.userType != "Admin"
  6.          {  
  7.             $rootScope.NotaValidUser = true;  
  8.             $location.path("");  
  9.         }  
  10.         else {  
  11.             $rootScope.NotaValidUser = false;  
  12.         }  
  13.         if ($rootScope.userType == undefined)
  14.        {  
  15.             $rootScope.NotaValidUser = false;  
  16.         }  
  17.     });  
  18. })  

You can see that I have checked whether the user is "Admin" or not; if not, then actions are taken accordingly. I will just show him some message and will not allow him to see any other content.

You can redirect the user to some other page using $location.path(). For example, $location.path("/Dashboard");

Now our sample application is created and it's time to run it.

Output

On running the application two textboxes appear with a submit button.


Firstly, I provided the Admin's user name and password and checked whether everything is working fine or not, you can see that two hyperlinks appeared:



As I click on any of them partial view is shown:


After this I provided some other user name who has limited authorization and again hyperlinks appeared:


But if I click on any of the links then a message is displayed, then:


If any non-existing user tries to enter, then nothing is shown to him: