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
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.
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.
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.
Instead of using ng-view, we will use ui-view.
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
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.
- var app = angular.module("Demo", ["ui.router"])
- .config(function($routeProvider, $locationProvider) {
- $routeProvider.caseInsensitiveMatch = true;
-
- $routeProvider
-
- .when("/home", {
- template: "<h1>Hello There !!</h1>",
- controller: "homeController as homeCtrl"
- })
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.
- var app = angular.module("Demo", ["ui.router"])
- .config(function($stateProvider) {
- // $routeProvider.caseInsensitiveMatch = true;
-
- $stateProvider
-
- .state("home", {
- url: "/home",
- template: "Templates/home.html",
- controller: "homeController as homeCtrl"
- })
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.
- .state("courses", {
- url: "/state",
- templateUrl: "Templates/courses.html",
- controller: "coursesController as coursesCtrl",
-
- })
-
- .state("students", {
- url: "/students",
- templateUrl: "Templates/students.html",
- controller: "studentsController as studentsCtrl",
- resolve: {
- studentsList: function($http) {
- return $http.get("StudentService.asmx/GetAllStudents")
- .then(function(response) {
- return response.data;
- })
- }
-
- }
- })
Let’s go down to our studentsController. In that, we need to make a change.
- .controller("studentsController", function(studentsList, $route, $location) {
- var vm = this;
- vm.searchStudents = function() {
- if (vm.name) {
- $location.url("/studentsSearch/" + vm.name);
- } else {
- $location.url("/studentsSearch/");
- }
-
- }
-
- vm.reloadData = function() {
- $route.reload();
- }
- vm.students = studentsList;
- })
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 ChangeIn our Viewindex.html, we used "a href" attribute for hyperlinks. Here, instead of "a href", we will use "ui-sref" attribute.
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.
- .state("home", {
- url: "/home",
- template: "Templates/home.html",
- So our final script file code is
- /// <reference path="angular.min.js" />
- /// <reference path="angular-route.min.js" />
-
- var app = angular.module("Demo", ["ui.router"])
- .config(function($stateProvider) {
- // $routeProvider.caseInsensitiveMatch = true;
-
- $stateProvider
- .state("home", {
- url: "/home",
- templateUrl: "Templates/home.html",
- controller: "homeController as homeCtrl"
- })
-
- .state("courses", {
- url: "/courses",
- templateUrl: "Templates/courses.html",
- controller: "coursesController as coursesCtrl",
-
- })
-
- .state("students", {
- url: "/students",
- templateUrl: "Templates/students.html",
- controller: "studentsController as studentsCtrl",
- resolve: {
- studentsList: function($http) {
- return $http.get("StudentService.asmx/GetAllStudents")
- .then(function(response) {
- return response.data;
- })
- }
-
- }
- })
-
- // .when("/students/:id", {
- // templateurl: "templates/studentdetail.html",
- // controller: "studentdetailcontroller as studentdetailctrl"
- // })
-
- // .when("/studentssearch/:name?", {
- // templateurl: "templates/studentssearch.html",
- // controller: "studentssearchcontroller as studentssearchctrl"
- // })
- // .otherwise({
- // redirectto: "/home"
- // })
- // $locationprovider.html5mode(true);
- })
-
- .controller("homeController", function() {
- this.message = "Home Page";
- })
-
- .controller("coursesController", function() {
- this.courses = ["c#", "SQL", "Oracle"];
- })
-
- .controller("studentsController", function(studentsList, $state, $location) {
- var vm = this;
- vm.searchStudents = function() {
- if (vm.name) {
- $location.url("/studentsSearch/" + vm.name);
- } else {
- $location.url("/studentsSearch/");
- }
-
- }
-
-
- vm.reloadData = function() {
- $state.reload();
- }
- vm.students = studentsList;
-
- })
-
- // .controller("StudentDetailController", function ( $http, $routeParams) {
- // var vm = this;
- // $http({
- // url: "StudentService.asmx/GetStudents",
- // params: { id: $routeParams.id },
- // method:"get"
- // })
- // .then(function (response) {
- // vm.student = response.data;
- // })
- // })
-
- //.controller("studentsSearchController", function ($http, $routeParams) {
- // var vm = this;
-
- // if ($routeParams.name) {
- // $http({
- // url: "StudentService.asmx/GetStudentsByName",
- // params: { name: $routeParams.name },
-
- // })
- //.then(function (response) {
- // vm.students = response.data;
- //})
- // }
- // else {
- // $http.get("StudentService.asmx/GetAllStudents")
- // .then(function (response) {
- // vm.students = response.data;
- // })
- // }
This is our View code.
- <!DOCTYPE html>
- <html ng-app="Demo">
-
- <head>
- <title></title>
- <base href="/" />
-
- <script src="scripts/angular.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.18/angular-ui-router.js"></script>
- <link href="Styles.css" rel="stylesheet" />
- <script src="scripts/script.js"></script>
-
- </head>
-
- <body>
- <table>
- <tr>
- <td colspan="2" class="header">
- <h1> Demo Application</h1>
- </td>
- </tr>
- <tr>
- <td class="leftMenu">
- <a ui-sref="home">Home</a>
- <a ui-sref="courses">Courses</a>
- <a ui-sref="students">Students</a>
- </td>
- <td class="mainContent">
- <ui-view></ui-view>
- </td>
- </tr>
- <tr>
- <td colspan="2" class="footer">
- <h1>
- Demo Application
- </h1>
- </td>
- </tr>
- </table>
- </body>
-
- </html>
Now, let’s save our changes and reload the page.
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.
Now, let’s check the reload button on the studentsController.
When we click on reload.
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.
Save the changes and reload the page.
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,
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 !!