AngularJS UI-Router HTML5 Mode And Active State CSS

In this article, you will learn about AngularJS UI-Router HTML5 Mode and Active State CSS.

Overview

In this article, we will see UI-Router HTML5 Mode and Active State CSS in AngularJS, with an example.

For more articles on AngularJS, do refer to these links-

Process

Step- 1
The first step is pretty simple. To enable HTML5 Mode, we will be using $locationProvider service in config function and setting this to true. Let’s see how.
  1. .config(function ($stateProvider, $urlMatcherFactoryProvider, $urlRouterProvider,$locationProvider)   
Set this $locationProvider service as true.

$locationProvider.html5Mode(true);


So, our final Controller code is the following.
  1. /// <reference path="angular.min.js" />  
  2. /// <reference path="angular-route.min.js" />  
  3.   
  4. var app = angular.module("Demo", ["ui.router"])  
  5.                     .config(function ($stateProvider, $urlMatcherFactoryProvider, $urlRouterProvider,$locationProvider) {  
  6.                         //  $routeProvider.caseInsensitiveMatch = true;  
  7.                         $urlRouterProvider.otherwise("/home");  
  8.                         $urlMatcherFactoryProvider.caseInsensitive(true);  
  9.                         $stateProvider  
  10.                         .state("home", {  
  11.                             url: "/home",  
  12.                             templateUrl: "Templates/home.html",  
  13.                             controller: "homeController as homeCtrl",  
  14.                             data:{  
  15.                                 customData1: "Home State Custom Data 1",  
  16.                                 customData2:"Home Statae custom Data 2"  
  17.   
  18.                         }  
  19.                         })  
  20.   
  21.                           .state("courses", {  
  22.                               url: "/courses",  
  23.                               templateUrl: "Templates/courses.html",  
  24.                               controller: "coursesController as coursesCtrl",  
  25.                               data: {  
  26.                                   customData1: "Courses State Custom Data 1",  
  27.                                   customData2: "Courses Statae custom Data 2"  
  28.   
  29.                               }  
  30.   
  31.                           })  
  32.   
  33.                            .state("students", {  
  34.                                url: "/students",  
  35.                                templateUrl: "Templates/students.html",  
  36.                                controller: "studentsController as studentsCtrl",  
  37.                                resolve: {  
  38.                                    studentsList: function ($http) {  
  39.                                        return $http.get("StudentService.asmx/GetAllStudents")  
  40.                       .then(function (response) {  
  41.                           return response.data;  
  42.                       })  
  43.                                    }  
  44.   
  45.                                }  
  46.                            })  
  47.   
  48.                                        .state("studentDetails", {  
  49.                                            url: "/students/:id",  
  50.                                            templateUrl: "Templates/studentDetail.html",  
  51.                                            controller: "studentdetailcontroller as StudentDetailCtrl"  
  52.                                        })  
  53.   
  54.                         //              .when("/studentssearch/:name?", {  
  55.                         //                  templateurl: "templates/studentssearch.html",  
  56.                         //                  controller: "studentssearchcontroller as studentssearchctrl"  
  57.                         //              })  
  58.                         //    .otherwise({  
  59.                         //        redirectto: "/home"  
  60.                         //    })  
  61.                         $locationProvider.html5Mode(true);  
  62.                     })  
  63.   
  64.                 .controller("homeController"function ($state) {  
  65.                     this.message = "Home Page";  
  66.                     this.homeCustomData1 = $state.current.data.customData1;  
  67.                     this.homeCustomData2 = $state.current.data.customData2;  
  68.                     this.coursesCustomData1 = $state.get("courses").data.customData1;  
  69.                     this.coursesCustomData2 = $state.get("courses").data.customData2;  
  70.                 })  
  71.   
  72.                  .controller("coursesController"function () {  
  73.                      this.courses = ["c#""SQL""Oracle"];  
  74.                  })  
  75.   
  76.                 .controller("studentsController"function (studentsList, $state, $location) {  
  77.                     var vm = this;  
  78.                     vm.searchStudents = function () {  
  79.                         if (vm.name) {  
  80.                             $location.url("/studentsSearch/" + vm.name);  
  81.                         }  
  82.                         else {  
  83.                             $location.url("/studentsSearch/");  
  84.                         }  
  85.   
  86.                     }  
  87.   
  88.   
  89.                     vm.reloadData = function () {  
  90.                         $state.reload();  
  91.                     }  
  92.                     vm.students = studentsList;  
  93.   
  94.                 })  
  95.   
  96.      .controller("studentdetailcontroller"function ($http, $stateParams) {  
  97.          var vm = this;  
  98.          $http({  
  99.              url: "StudentService.asmx/GetStudents",  
  100.              method: "get",  
  101.              params: {id:$stateParams.id}  
  102.          })  
  103.      .then(function (response) {  
  104.          vm.student = response.data;  
  105.      })  
  106.      })  
  107.   
  108. //.controller("studentsSearchController", function ($http, $routeParams) {  
  109. //    var vm = this;  
  110.   
  111. //    if ($routeParams.name) {  
  112. //        $http({  
  113. //            url: "StudentService.asmx/GetStudentsByName",  
  114. //            params: { name: $routeParams.name },  
  115.              
  116. //        })  
  117. //.then(function (response) {  
  118. //    vm.students = response.data;  
  119. //})  
  120. //    }  
  121. //    else {  
  122. //        $http.get("StudentService.asmx/GetAllStudents")  
  123. //                 .then(function (response) {  
  124. //                     vm.students = response.data;  
  125. //                 })  
  126. //    }  
Step- 2 Now, our second step is to remove the # symbols from URLS. To build the URL, we are using ui-sref attribute instead of href attribute. So, go to the index.html.



As you can see, we are using si-sref attribute and we don’t have any # symbols there. Similarly, we don’t have any # symbols in students.html and studentsdetail.html files.

Step- 3 Now, the next step is to include re-write routing rule in our web.config file. So, just copy paste this code in your file.
  1. <system.webServer>  
  2.     <rewrite>  
  3.       <rules>  
  4.         <rule name="RewriteRules" stopProcessing="true">  
  5.           <match url=".*"/>  
  6.           <conditions logicalGrouping="MatchAll">  
  7.             <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true"/>  
  8.             <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true"/>  
  9.             <add input="{REQUEST_URI}" pattern="^/(api)" negate="true"/>  
  10.           </conditions>  
  11.           <action type="Rewrite" url="/index.html"/>  
  12.         </rule>  
  13.       </rules>  
  14.     </rewrite>  
  15.       
  16.   </system.webServer>  
This rewrite rule will rewrite all the requests to index.html.
  1. <action type="Rewrite" url="/index.html"/>  
The index.html file is our layout page. Except, if the request is for a file or a directory or it’s a web api,

Step- 4 Now, the final step is to include base href=”/” in your layout page which we already have. Now, let’s save our changes and run the app.

As you can see in the URL, the # symbol has disappeared. Now, the HTML5 Mode is in action. See the output below.



Similarly, for courses and students, the # symbol has disappeared, which means that we have successfully enabled the HTML5 routing in our application.

NOTE - The base href element makes sure that you place it below the title element.



If the base href element is placed anywhere else, it will not search for the / root directory when you reload the Controller.
 
Part -2 

Now, let's move to the next part of this article i.e Active State CSS.

In this section, we will see how to highlight the navigation menu item if the user is currently on that page. Suppose, when the user clicks on the home page, we want the home to be highlighted, and similar effect for the courses and students pages. Let’s see how to do that.

1. First, we include a CSS class that we want to apply to the active menu items. We will create a CSS class in styles.css.

  1. .activeState {  
  2. background-color:orangered;  
  3. color:white;  
  4.   
  5. }  
So, it’s a pretty straightforward CSS class with two properties. The class name is active and its properties are background color and text color, which should be any color and white, respectively.

2. The next step is to modify the links in the index.html. In that, we will apply a different directive to those links.



This directive will apply two things automatically to the state that is active. It will automatically remove that class from any state that has become inactive. So, with these changes we should get the desired output.

3. Save the changes and reload the app.



As you can see from the above output, currently I am in Home Controller and it highlighted the Home menu which is currently active. So, we got the desired result for home. Now, let’s check it for other Controllers as well.

For courses,



And, for Students,



Conclusion - So, this was all about AngularJS UI-Router HTML5 Mode and active State CSS. Hope this article was helpful!!