Easier Angular JS Routing With Angular UI Router

Read it in 8 Mins

Last updated on
07th Jun, 2022
Published
25th Sep, 2020
Views
6,658
Easier Angular JS Routing With Angular UI Router

Takeaways from this article 

  • In this post, we will understand how and why Angular JS Routing is better in comparison to traditional frameworks, and how this routing can be achieved seamlessly with the help of Angular UI Router.  
  • We will understand the usage and importance of states, and how they help in navigating easily through the application. 
  • We will see a sample with a state definition and its usage, and how it helps in resolving issues and making the page user-friendly.  

Introduction

Angular JS is a popular application framework that is used for front-end development. It works great when creating single page applications. It is written in JavaScript and is being maintained by tech-giant Google. It is used to interpret the HTML attributes in a webpage in the form of directives and bind the respective input and output components of the model, that are represented in the form of JavaScript variables. Angular UI Routing helps navigate between views and pages seamlessly without getting messy, and in a user-friendly manner.  

Know more about angular cli.

Note: It is assumed that the reader is aware of technologies like HTML, CSS, JavaScript and Angular JS. 

Native Angular Routing doesn’t have the following facilities: 

  • No nested views 
  • No named views 
  • Data can’t be passed around between two views 
  • The syntax of the route should be literally remembered to navigate the page 
  • The URL string has to be manually changed via the code base when a URL is changed. When a URL changes, all the links associated with that URL have to be changed and updated to point to the new location.  

In order to minimize the above disadvantages, Angular UI Router is used.  

Introduction to Angular JS Routing 

Angular JS Routing is an advanced technique that helps in routing, that has a declarative approach in navigating through the pages of a website. In a webpage, when a link that points to a different page is created, the URL has to be explicitly defined. This path has to be literally memorized and if it is changed, then the URL would have to be changed in all places where it was previously referenced. This is when Angular JS Routing comes into play.  

Angular UI Router is a module in Angular JS that helps in the process of routing in Angular JS applications. The Router facilitates in the creation as well as usage of such routes in applications. 

The Router consists of a method called ‘stateProvider’ which helps in the creation of ‘states’, also known as ‘routes’.  The method ‘stateProvider’ takes the name of the state and the configurations of the state as its parameters. It looks like below:

$stateProvider.state(stateName, stateConfig)

The above function creates a state in the application. The parameter ‘stateName’ is a string value that is used to create a parent or a child state. To create a child state, the parent state is referenced with the help of the dot operator.  

The ‘stateConfig parameter is an object that can take many properties, such as: 

  • templateIt is a string in the form of HTML content or a function that returns a HTML string as the output.  
  • templateUrl: It is a string that is a URL path to a specific template file or a function that returns a URL path string as the output.  
  • templateProvider: It is a function that returns the HTML content as a string output.  

Note: The ‘stateConfig’ parameter can take only one property at a time per state or per view with respect to the application.  

The states in an application help the user in navigating or reconstituting to the situation that occurs within the application’s working. 

Note: The latest version of UI Router can be downloaded from the GitHub repository. 

Below are three examples when ‘stateConfig’ has different properties: 

With ‘template’ as a property: 

$stateProvider.state(‘stateName’,   
{ 
     url: ‘url for the specific state’, 
    template: ‘html content’, 
    controller: "name of controller for specific state" 
});

With ‘templateUrl’ as a property:

$stateProvider.state('stateName',  
{
    url: ‘url for the specific state’,
    templateProvider: ‘function name’,
    controller: "name of controller for specific state"
});

Introduction to Angular JS Router 

  • It is one of the modules in Angular JS that helps in creating routes for applications that use Angular JS.  
  • Applications are encompassed in a shell, and this shell behaves like a placeholder for the dynamic content that would be generated later.  
  • The UI Router is a routing framework that changes the views of the application based on not just the URL, but the state of the application as well.  
  • It helps in bridging the gap between the traditional frameworks, by allowing nested views, named views, passage of data between two different views, and so on.  
  • Routes are an integral part of Single Page Applications that are preferably created using Angular JS.  
  • With the help of Angular UI Router, these routes can be created with ease and can be used with ease in Angular JS.  
  • The ‘state’ facility gives the flexibility to encapsulate the location of the URL state name, special data for view, generate a view, or even locate a view.  
  • Angular UI Router consists of a ‘stateProvider’ method that can be used to create a route or a state in an application.  
  • The stateProvider function takes the name of the state and the configurations of the state as its parameter.  
  • In addition to this, Angular UI Router also helps resolve dependencies before initializing the controller.  
  • It provides utility filters, declarative transitions, state change events, and so on.  

What is the difference between State and URL Routes? 

State Route 

The views and routes of the Angular JS page will not be bound with just the URL of the site. The specific parts of the site can be changed with the help of UI Routing even if the URL has been kept the same. All the states, routing, and viewing capabilities of the page are handled at a single one-stop place- the ‘.config()’. 

URL Route 

URL route is a little different. It is usually implemented using ‘ngroute’, and it needs the implementation of methods such as ‘nginclude’. If the number of methods increases, the situation could get complicated and handling of these methods gets difficult.

Stepwise routing with detailed explanation

  • The node.js and npm have to be installed prior to working with the below steps.  
  • For this purpose, the http-server node module has to be run and installed which will help in hosting the demo application that we would create.  
  • It can be installed with the help of the below command: 
npm install http-server –g
  • A hierarchical directory structure needs to be created. A sample has been shown below:
Demo_App
--app.js
--index.html
--nav.html
  • The ‘nav.html’ file needs to have the content as mentioned below: 
    • The nav bar title 
    • The contents of the file  
    • The two different actions that would be created will also be mentioned here (The home page and the log in.) 
  • The index.html file will have the required dependencies along with nav.html file.  
  • The nav.html file will be included in the body tag of the index.html page. 
  • The dependencies will be included with the help of ‘CDN’ in the head tag. A separate body tag will be used to define the ui-view div. 
  • The ui-view is a section where the information about various routes content and how they would be rendered is present 
  • The ui-view is a directive that is present inside the ui.router module.  
  • The ui-view directive tells the ‘$state’ about the positioning of the template properties (or other property) 

It would look like below (sample): 

<script src="angular.name.js"> 
</script> 
<script src = "https://unpkg.com/@uirouter/angularjs@1.0.7/release/angular-ui-router.min.js"> 
</script>
  • An app.js file can be created, which is an application file that contains the route information and the actions that need to be performed with the help of the controller in the application framework. Below is a sample app.js file:
var app = angular.module('Demo_App', [ "ui.router" ]);   
app.config(function($stateProvider, $locationProvider,   
                                $urlRouterProvider)   
{   
    $stateProvider.state('home_page',   
{   
            url : '/home',   
            template : "<h1>Home page</h1>",   
            controller : "hmeCtrl" 
        })   
        .state('login_page',   
{   
            url : '/login',   
            template : "<h1>Login page</h1>",   
            controller : "lgnCtrl" 
        })   
    $urlRouterProvider.otherwise("/home");   
});   
app.controller('mainCtrl', function() {});   
app.controller('hmeCtrl', function() {});   
app.controller('lgnCtrl', function() {});
  1. The first line of the sample code declares the name of the application module and injects a ui.router module dependency into it. 
  2. Next, the route configurations are defined inside the app.config and the dependency injections are set up.  
  3. The routes for the required attributes are set up with the help of the ‘stateProvider’ function and mentioning the required parameters.  
  4. Once the home page and the login have been set up, a condition is set up where the page would be redirected back to the home page if any of the routes don’t match the url name. This is done with the help of the ‘otherwise’ function.   
  5. Empty states are created for the controllers. This is done since it is a sample and no operation is being performed inside these states.  
  • The above sample application can be run in the browser after the http-serve node module has been installed (as mentioned in the first step of this explanation).  
  • Next step is to navigate to the ‘routingDemo’ folder and execute the below mentioned command:
http-server
  • This command helps in hosting the demonstration application on the default port that is 8080. This can be accessed with the help of the below mentioned link:
localhost:8080/
  • When the application is accessed via a browser, it will be a web application with two routes, namely:
    • Home
    • Login

Conclusion

In this post, we understood the prominence of Angular JS Routing and Router, and how they are different from the traditional approaches. They help bridge a gap between the features that traditional approaches implement, thereby increasing the ability of web pages to work and perform in a better, more user-friendly manner.


Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Profile

Amit Diwan

Author

Amit Diwan is an E-Learning Entrepreneur, who has taught more than a million professionals with Text & Video Courses on the following technologies: Data Science, AI, ML, C#, Java, Python, Android, WordPress, Drupal, Magento, Bootstrap 4, etc.