AngularJS UI-Router And Configuring States

Overview

In this article, we will learn about UI Router, where to get UI-Router module from, and how to include it in an Angular application.

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

What is UI-Router

  • The UI-Router is a third-party routing framework for AngularJS. It provides many additional features which are very useful for larger applications.

  • UI-Router implements routing based on the state of the application just like ngRoute implements routing based on the route URL. But, unlike ng-route, the UI-Router is not tied with the application URL.

The CDN link for UI-Router is - 

  • https://cdnjs.com/libraries/angular-ui-router

    1
There are 3 simple steps to include UI-Router in your application. 
  • Reference the UI-Router CDN link.
  • Add UI-Router as Module dependency.
  • Add UI-View directive in page layout.

So, we will follow these steps.

First, we will copy the CDN link and reference it in our application.
 
2
Second, add UI-Router as Module dependency, In our script.js file, there are no dependencies there. So, we add that dependency as ui.router.
3 

The final step is to add the UI View directive in layout page which, in our case, is index.html. At the moment, we have these ngView directives where our partial templates will be injected.
 
 
4 
Instead of using ng-view, we will use ui-view. 

5 
Now, let's see UI-Router Configuring States.

What is a State?

State corresponds to a "Place" in your Angular application. As this statement does not make sense at the moment, I will clear up this concept in upcoming articles.

How to configure a State

To configure a state, use state () method of $stateProvider service. This method has two parameters stateName and stateConfig.
 
stateName is a unique state name. For example: it can be /home, /courses, /students, and so on.

stateConfig is the state configuration object with several properties, such as - templates, templateURL, Controller, Controller AS, and ResolveURL etc.

Current Output
 
6 
This is our current output after using UI-Router. Notice that when we click on any link, nothing happens, because these are broken links. Let's fix these links.

Let’s go back to script.js file as we are using $routeProvider. These methods are provided by ng-scope but we are no more using ng-scope directive. We are using ng-route.
  1. var app = angular.module("Demo", ["ui.router"])  
  2.     .config(function($routeProvider, $locationProvider) {  
  3.             $routeProvider.caseInsensitiveMatch = true;  
  4.   
  5.             $routeProvider  
  6.   
  7.                 .when("/home", {  
  8.                 template: "<h1>Hello There !!</h1>",  
  9.                 controller: "homeController as homeCtrl"  
  10.             })  
We will use $stateProvider service and .state method. I am commenting some of the code in the script.js file. This is the sample of how to configure a state, we do it for homeController.
  1. var app = angular.module("Demo", ["ui.router"])  
  2.     .config(function($stateProvider) {  
  3.             // $routeProvider.caseInsensitiveMatch = true;  
  4.   
  5.             $stateProvider  
  6.   
  7.                 .state("home", {  
  8.                 url: "/home",  
  9.                 template: "Templates/home.html",  
  10.                 controller: "homeController as homeCtrl"  
  11.             })  
Here, we used .state method and in that, it has a unique name as home and the URL as /home is same for the courses and students.
  1. .state("courses", {  
  2.     url: "/state",  
  3.     templateUrl: "Templates/courses.html",  
  4.     controller: "coursesController as coursesCtrl",  
  5.   
  6. })  
  7.   
  8. .state("students", {  
  9.     url: "/students",  
  10.     templateUrl: "Templates/students.html",  
  11.     controller: "studentsController as studentsCtrl",  
  12.     resolve: {  
  13.         studentsList: function($http) {  
  14.             return $http.get("StudentService.asmx/GetAllStudents")  
  15.                 .then(function(response) {  
  16.                     return response.data;  
  17.                 })  
  18.         }  
  19.   
  20.     }  
  21. })  
Let’s go down to our studentsController. In that, we need to make a change.
  1. .controller("studentsController", function(studentsList, $route, $location) {  
  2.     var vm = this;  
  3.     vm.searchStudents = function() {  
  4.         if (vm.name) {  
  5.             $location.url("/studentsSearch/" + vm.name);  
  6.         } else {  
  7.             $location.url("/studentsSearch/");  
  8.         }  
  9.   
  10.     }  
  11.   
  12.     vm.reloadData = function() {  
  13.         $route.reload();  
  14.     }  
  15.     vm.students = studentsList;  
  16. })  
Now, in the studentsController, we are using route service for the entire application. But, this route service is provided by ng-route module. As we have removed the ng-route from the script,  this reload functionality is not going to work.

To make it work, we will use $state service that is provided by UI- Router module. This $state service has in-built reloaded method, just to reload the current state instead of loading the entire app.

The Final Change

In our Viewindex.html, we used "a href" attribute for hyperlinks. Here, instead of "a href", we will use "ui-sref" attribute.
7 
With ui-sref attribute, the link is going to be the name of the state not the URL. So, when home state is activated, it will search for the script file and will be redirected to this.
  1. .state("home", {  
  2.             url: "/home",  
  3.             template: "Templates/home.html",  
  4.             So our final script file code is  
  5.             /// <reference path="angular.min.js" />  
  6.             /// <reference path="angular-route.min.js" />  
  7.   
  8.             var app = angular.module("Demo", ["ui.router"])  
  9.                 .config(function($stateProvider) {  
  10.                     // $routeProvider.caseInsensitiveMatch = true;  
  11.   
  12.                     $stateProvider  
  13.                         .state("home", {  
  14.                             url: "/home",  
  15.                             templateUrl: "Templates/home.html",  
  16.                             controller: "homeController as homeCtrl"  
  17.                         })  
  18.   
  19.                     .state("courses", {  
  20.                         url: "/courses",  
  21.                         templateUrl: "Templates/courses.html",  
  22.                         controller: "coursesController as coursesCtrl",  
  23.   
  24.                     })  
  25.   
  26.                     .state("students", {  
  27.                         url: "/students",  
  28.                         templateUrl: "Templates/students.html",  
  29.                         controller: "studentsController as studentsCtrl",  
  30.                         resolve: {  
  31.                             studentsList: function($http) {  
  32.                                 return $http.get("StudentService.asmx/GetAllStudents")  
  33.                                     .then(function(response) {  
  34.                                         return response.data;  
  35.                                     })  
  36.                             }  
  37.   
  38.                         }  
  39.                     })  
  40.   
  41.                     // .when("/students/:id", {  
  42.                     // templateurl: "templates/studentdetail.html",  
  43.                     // controller: "studentdetailcontroller as studentdetailctrl"  
  44.                     // })  
  45.   
  46.                     // .when("/studentssearch/:name?", {  
  47.                     // templateurl: "templates/studentssearch.html",  
  48.                     // controller: "studentssearchcontroller as studentssearchctrl"  
  49.                     // })  
  50.                     // .otherwise({  
  51.                     // redirectto: "/home"  
  52.                     // })  
  53.                     // $locationprovider.html5mode(true);  
  54.                 })  
  55.   
  56.             .controller("homeController", function() {  
  57.                 this.message = "Home Page";  
  58.             })  
  59.   
  60.             .controller("coursesController", function() {  
  61.                 this.courses = ["c#", "SQL", "Oracle"];  
  62.             })  
  63.   
  64.             .controller("studentsController", function(studentsList, $state, $location) {  
  65.                 var vm = this;  
  66.                 vm.searchStudents = function() {  
  67.                     if (vm.name) {  
  68.                         $location.url("/studentsSearch/" + vm.name);  
  69.                     } else {  
  70.                         $location.url("/studentsSearch/");  
  71.                     }  
  72.   
  73.                 }  
  74.   
  75.   
  76.                 vm.reloadData = function() {  
  77.                     $state.reload();  
  78.                 }  
  79.                 vm.students = studentsList;  
  80.   
  81.             })  
  82.   
  83.             // .controller("StudentDetailController", function ( $http, $routeParams) {  
  84.             // var vm = this;  
  85.             // $http({  
  86.             // url: "StudentService.asmx/GetStudents",  
  87.             // params: { id: $routeParams.id },  
  88.             // method:"get"  
  89.             // })  
  90.             // .then(function (response) {  
  91.             // vm.student = response.data;  
  92.             // })  
  93.             // })  
  94.   
  95.             //.controller("studentsSearchController", function ($http, $routeParams) {  
  96.             // var vm = this;  
  97.   
  98.             // if ($routeParams.name) {  
  99.             // $http({  
  100.             // url: "StudentService.asmx/GetStudentsByName",  
  101.             // params: { name: $routeParams.name },  
  102.   
  103.             // })  
  104.             //.then(function (response) {  
  105.             // vm.students = response.data;  
  106.             //})  
  107.             // }  
  108.             // else {  
  109.             // $http.get("StudentService.asmx/GetAllStudents")  
  110.             // .then(function (response) {  
  111.             // vm.students = response.data;  
  112.             // })  
  113.             // }  
This is our View code.
  1. <!DOCTYPE html>  
  2. <html ng-app="Demo">  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <base href="/" />  
  7.   
  8.     <script src="scripts/angular.min.js"></script>  
  9.     <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>  
  10.     <link href="Styles.css" rel="stylesheet" />  
  11.     <script src="scripts/script.js"></script>  
  12.   
  13. </head>  
  14.   
  15. <body>  
  16.     <table>  
  17.         <tr>  
  18.             <td colspan="2" class="header">  
  19.                 <h1> Demo Application</h1>  
  20.             </td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td class="leftMenu">  
  24.                 <a ui-sref="home">Home</a>  
  25.                 <a ui-sref="courses">Courses</a>  
  26.                 <a ui-sref="students">Students</a>  
  27.             </td>  
  28.             <td class="mainContent">  
  29.                 <ui-view></ui-view>  
  30.             </td>  
  31.         </tr>  
  32.         <tr>  
  33.             <td colspan="2" class="footer">  
  34.                 <h1>  
  35.                     Demo Application  
  36.                 </h1>  
  37.             </td>  
  38.         </tr>  
  39.     </table>  
  40. </body>  
  41.   
  42. </html>  
Now, let’s save our changes and reload the page.
 
 8

When I click on home, notice the URL above. We are routing our respective URLs. Now, let’s check the reload functionality in studentsController. We will insert a record from database.
 
9

Now, let’s check the reload button on the studentsController.
 
10
When we click on reload.
 
11

The name Ashok has appeared in our studentsController. Now, let’s comment on some of the properties of our Controller. We will comment the URL property of each Controller. 
 
12 

Save the changes and reload the page.
 
13

As you can see, the hyperlinks are not there. This is because their respective states do not have a URL property. So, it didn’t generate href attribute of that respective Controller.

But when you click on home, the state object is instantiated. Let's see how. Click on home and you will see,
 
14 
As you can see, the homeController is loaded. But, look at the URL above; It does not change because the URLs do not have the state's properties. The same thing happens with courses and students Controller too.

Conclusion

So, this was all about UI-Router and configuring States in AngularJS. Hope this article was helpful !!