e-Zest members share technology ideas to foster digital transformation.

Effective Routing & Navigation in AngularJS Application

Written by Ashwini Eksambekar | Nov 9, 2016 9:33:42 AM

AngularUI Router is a routing framework for AngularJS, mainly developed to improve as well as enhance routing capabilities. It allows us to well organize the parts of application interface into a state machine. UI-Router is state-based framework making routing and UI navigation easier and manageable. The $route service in Angular core is organized around URL routes whereas UI-Router is organized around states. It may optionally have routes and other behaviour, attached with it.

States are bound to named, nested and parallel views that allow us to powerfully manage our application's interface

Initial steps to use AngularUI Router :

  1. Simply, we can download angular-ui-router.js file from link http://angular-ui.github.io/ui-router/release/angular-ui-router.js or angular-ui-router.min.js (minified file) from link http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js .
  1. Include angular-ui-router.js (or angular-ui-router.min.js) in your index.html file where we include AngularJS itself

Configuring our application with AngularUI Router :

Let’s begin configuring our application with AngularUI Router.

  1. Inside of our app.js file, we need to add a dependency on the ui-router to our main angular module. e.g.

angular.module ( ‘ myUiRoutingApp ’ ,  [ 'ui.router'] )

      2. After that we need to inject $stateProvider and $urlRouterProvider into our config object.

angular.module(‘myUiRoutingApp’, ['ui.router'])

.config ([ '$stateProvider', '$urlRouterProvider',

function( $stateProvider, $urlRouterProvider ) {

$urlRouterProvider.otherwise('/home');

$stateProvider

.state ('home', {

url: "/home",

templateUrl: "modules/main/views/home.html"

})

.state ('user', {

url: "/user",

templateUrl: "modules/user/views/user.html"

})

.state ('user.newUser', {

url: "/newUser'",

templateUrl: "modules/user/views/newUser.html"

}) }


]);

In example above $urlRouterProvider.otherwise(), is used to map our application to home state by default whereas $stateProvider is used to define states.

A state is nothing but a place in the application in terms of the overall UI and navigation perspective. It describes view (html template) it renders as well as how and what UI looks like at that place.

// $stateProvider ‘s state() method take unique stateName (String) and a stateConfig (Object)

$stateProvider.state( stateName, stateConfig);

Let’s have a look at some parameters often used to define state object.
These parameters for $stateProvider‘s .state () method are:

  • stateName (String)

This is unique name describing state, e.g. "home”, “settings” etc. Usually stateName corresponds to view it renders. For having an inheritance based nesting of states that is for creating parent/child states, we use a dot notation. Example: "settings.profile", "user.newUser". Such states are defined when using nested states and nested views.

  • stateConfig (Object)

The stateConfig object can be defined using following properties.

  • template It represents String HTML content, or function that returns an HTML content .
  • templateUrl – It represents String URL path to HTML template file OR the directive will automatically generate & update the href function which returns URL path string.
  • templateProvider – It represents function that  returns HTML content string.
  • Controller It represents a controller paired to the state as controller function or its name as string
  • controllerProvider It represents Function (injectable) that returns the actual controller function or string.
  • resolve The resolve object corresponds to a map of dependencies which should be injected into the controller. This has following format.
  1. keys – Refers to name of dependency to be injected into controller
  2. factory – [string|function] When given as string then it is alias for service. And when given as function being injected and returning value, then that value is treated as dependency. In case if result is a promise, it is resolved before value is injected into controller
  • views – It refers to object defining view This views property is used to set up multiple views. If we don't need multiple views within a single state then no need to use this property. Often using nested views is more useful and powerful than using multiple sibling views.

This views object has following format.

  1. keys – (string) name of ui-view
  2. view object– (object) view configuration object set up uses its own templates and respective controllers.

      3. Now we can add a ui-view directive to the <body /> of our app.
the ui-view is directive provided by the ui.router module. The ui-view directive gives information to $state like where to place our (views) templates. A view can be unnamed or named.
We can only have one unnamed view within any template. For having multiple views, we can do setup views property of $stateProvider’s state and use named views with ui-view directive. This can be better illustrated with following example.

<div ui-view=”headerPanel”></div>

<div ui-view="mainView"></div>

<div ui-view="footerPanel"></div>

$stateProvider.state ("home", {

    views: {

        "headerPanel": {

            template: "<h1> Header data </h1>"

        },

        "mainView": {

            template: “<div> main view data </div>"

        },

        "footerPanel": {

            template: "<div> Footer data </div>"

        }

    }   

      4. Further we can use ui-sref directive while navigation to particular state.

This directive binds a link (<a> anchor tag) to a state. If the state has an associated URL with it, then ui-sref directive automatically create and update the href attribute by using $state.href() method. Thus, click event to such a link will trigger a state transition with optional parameters.
Example:

HTML Template using ui-sref directive :

<a ui-sref="home">Home</a>

<a ui-sref="user.newUser">New User</a>

AngularUI Router usage benefits:

Ui-Router supports not only ngRoute but also adds many extra routing features.

  • ui-router allow us to have nested views & multiple named views. This feature is very useful with larger web apps where we may have pages which inherit from other different sections.
  • ui-router provides us strong-type linking between states with state names. Any change in the url in one place thus updates every link to that state when we build our links using ui-sref For larger projects where possibly URLs might change, this feature plays vital role.
  • States allow us to map, configure and access different information about different states and we can easily pass information between these states via $stateParams.
  • With ui-router, state transitions can be performed effectively using $state.go() or $state.transitionTo() etc. methods. State Change Events can be used as per application need. These are fired at rootScope level and are as follows:
  • $stateChangeStart - This event is fired when any state transition begins.
  • $stateNotFound - This event is fired when a requested state is not found on using its provided state name during any state transition.
  • $stateChangeSuccess - This event is fired once the state transition process completes.
  • $stateChangeError - This event is fired when any error occurs while state transition process.

Thus, In AngularJS applications for effective routing and navigation ui-router usage will be helpful.