Back to Top

AngularJS Routing Using UI-Router

angular js routing mechanism

Angular JS is very popular nowadays due to its simplicity and easy to implement.Routing in Angular Js makes the single page application aka Single Page APP(SPA) more popular. SPA is to switch to another view without refreshing the page and usually we use the ajax request to fetch the data from the background and render the HTML.

All MVC framework which is for frontend application has a routing feature because it is essential to building the single page application(SPA).

What is Routing?

Routing is a mechanism used to navigate through the deep link.You can organize the various views of a single page application(SPA) using routing mechanisms in well manner.

There are two types of Routing Mechanism in Angular JS

  1. Inbuilt Router
  2. UI Router

In-built Router(ngRoute)

ngRoute is an inbuilt Router which is provided by Angular using a hash and history. There are two ways to achieve the ngRoute.In Built ngRoute is simply routing a single URL which you can bind to the single controller with the single template.

ngRoute is a separate module which contains following:

$route – it is used for getting matched route, routing events such as access the current route controller and to provide property access

$routeProvider – It is used to define a routing table that the address bar and map the view template.Using $routeProvider Service, You can allow to save the API browsing history and allows users to save a bookmark of the current path for future use

$routeParams – It saves the parameter in address bar.

$routeProvider – routing table has two core methods

1.when (path, route)

This method takes two parameters:

Path is a string type which match with routing path rule. It will work with the address bar contents ($location.path) values to match. To match the parameters, you can use the colon in the path name.

Example:

when the method of $routeProvider can also handle the query string or id passed in the URL which you can pass after the /:number.$routeProvider will match URL id and the id as a key service used in the $routeParams

2. otherwise (params)

The otherwise method is useful to redirect to the user on the specific page if your routed page not found.

SYNTAX:

UI Router

As in built ngRoute has limited features so sometimes it can not meet the development needs! At that time, third-party routing module ui router comes in use. Let’s understand how UI Router useful.UI-Router in angular js is basically based on the state machine which provides the routing mechanism and nested functions.

What is UI Router?

UI-Router is not the ​inbuilt tool so we can say it is third party tool to develop features not available in inbuilt one.ngRoute does not provide Nesting and view named property.It allows state based URL to organize the UI rendering interface.It also allows a use of multiple views on the same page which improves the functionality of a view.UI-Router is an excellent way to manage the very complex web application.

Installation

For Installation of UI Router library, you can either use Bower or you can choose to download the release version.

Also you need the source file that contains the page:

Now, Let’s see the syntax inject the UI Router in your app. It is necessary to inject the UI Router in your app to use it.

Basic SYNTAX:

HTML Syntax for UI Router

Your content will be injected in between ui-view div.

Content Syntax for UI Router:

After body tag, add the above tag.

Here the file name is admin.html

Basic UI Router Syntax:

It is used in order to define any state in UI Router

$urlRouterProvider otherwise method is used to check if state not found, redirect user to the page passed in the otherwise() method.

What is the difference between inbuilt ngRoute and ui router?

1. The main difference between inbuilt ngRoute and UI Route. There are lot many difference but these are the basic benefits if anybody looking for when to use ui router, so these are the basic aspects:

2. The nested view which is not possible in ngRoute.

3. NgRoute can have single URL with single view whereas UI Router has state views so you have multiple URLs​ so you can create multiple views.

What is State and StateProvider?

A state is just a state machine which acts like state machine in the top of the ngRoute.Internally, It will manage state and based on state it will provide.$StateProvider (service provider) is used to configure the routing in Angular JS.

State V/S Route

StateRoute
A Place within AppA URL within App
Nested HierarchyFlat Hierarchy
Names are just namesNames are URLs
Multiple Views(ui-view)Single view (ng-view)
Populate any viewPopulate specific view
State populates ‘parts’Directive populates ‘parts’

Similarities

1. Associate a URL(optional in ui router)
2. You can apply a template/templateUrl
3. Can assign controller
4. Can resolve dependencies before controller initiates
5. Redirects using when()

Nesting (Nested Views):

Nesting is the main stuff of the UI Routing in Angular JS.It is a simple act of nesting makes ui for 90% of the zerg effect.If you have hierarchical URL, at that time nesting comes in implementation.

It’s like a component within component within the component.

Angular DOM is work on hierarchy as per the position of controller.The controller will inherit the nesting properties.The child name attribute will cover in the parent name attribute scope.

How Nesting achieved?

Each template is inserted into the ui-view of the parent state’s template.ui.router provides several ways to define its child routes:

1. Dot notation ( Recommended ) : How child state made

2. The ‘parent’property in config

Parent routed directly specified routes by parent argument and can be a parent route status name (string), can also be a state name that contains the configuration (object).

Here is a simple example of nested views.

This example defined in order to define any state in ui.router. Content on the page will be injected in between the ui-view element. If defined state not found, it will redirect to the admin state.

Angular provides two options

Object based States:

Inheritance:

It is angular being Angular. Child state inherits from the parents.Inheritance is not good sometimes because it overwrites the object’s properties.

Example

Inheritance Resolved Dependencies:

Dependency is used in order to share data between two controllers.You can use the resolve() method for the dependency injection. A resolve() method contains one or more promises that must resolve successfully before the route will change.

Activating a State:

1. Merge option with defaults
2. check if state is defined
3. Merge params with ancestor params(Unless option.inherit = false)
4. Figure out which states are changing and which aren’t (No transition, unless option.reload = true)
5. Broadcast $stateChangeStart. if event.default

How to activate State?

$state.go()

$state.go() method is the most advanced and convenient method.$state.go() the method is the latest method. .go doing lot many operations whereas the transition is not doing.

ui-sref

Navigate to the state URLs

Abstract States

Abstract means a state. It is not get activated by itself. It will be activated when any child of state will be activated. Everything you provided in the abstract state will be executed when its child state gets executed.

It is mainly used to resolve the common dependencies of all the child.

1. To prepend the URL to all child states URLs.
2. To insert a template with its own ui-view(s) that its child states will populate. For Example, Two parents having the different template you can render template accordingly.
3. Optionally assign the controller to a template.
4. To provide resolved dependencies for all child.

$stateParams Caveats:

Populated when state is activated and all the dependencies resolved(In resolved function, use $stateCurrentParams)

In State controllers, Its scope to only its parent state.

Multiple Named Views:

This is actually the main functionality of ui router.

Name your views so that you can have more than one ui-view per template.

Pros:

1. Flexibility
2. You get to have multiple views in any template
3. Single Top level component

Cons:

1. Often unnecessary.
2. It may create confusion.

Example:

Let’s see the live example to understand this:

HTML

JS

angular-UI-router based on the state machine that provides routing and a series of nested functions.

Here, I have introduced the routing mechanism in Angular JS.Also, I explained with the example when required in this article though if you have any query let me know via comment section. If you have found this article useful, please remember to share it with others on Facebook & Google+.

Do you use UI Router in your application? share how and where you have used UI Router of Angular JS?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts