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
- Inbuilt Router
- 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:
1 2 3 4 5 6 7 8 9 | angular.module('myApp', []). $routeProvider.when('/', { controller: 'HomeController', template: '<h2>We are home</h2>' }) }]); |
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
1 2 3 4 5 6 | $routeProvider.when('/person/:id', { controller: 'PersonController', template: '<div>Person Name is: {{ name }}</div>' }) |
2. otherwise (params)
The otherwise method is useful to redirect to the user on the specific page if your routed page not found.
1 2 3 4 5 6 7 8 9 10 | angular.module('myApp', []). config(['$routeProvider', function($routeProvider) { $routeProvider.when('/', { controller: 'HomeController', template: '<h2>We are home</h2>' }) .otherwise({redirectTo: '/'}); }]); |
SYNTAX:
1 2 3 | $routeProvider(current,single level) |
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.
1 2 3 | $ bower install angular-ui-router --save |
Also you need the source file that contains the page:
1 2 3 | <script type = "text/javascript" src = "app/bower_components/angular-ui-router/release/angular-ui-router.js"> </ script> |
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:
1 2 3 | module(‘myapp’,[‘ui.router’]).controller |
HTML Syntax for UI Router
1 2 3 4 5 | <div ng-controller = "DemoController"> <div ui-view></div> </div> |
Your content will be injected in between ui-view div.
Content Syntax for UI Router:
After body tag, add the above tag.
1 2 3 | <a ui-sref="admin">Admin</a> |
Here the file name is admin.html
Basic UI Router Syntax:
It is used in order to define any state in UI Router
1 2 3 4 5 6 7 8 9 10 | .module(‘myapp’,[‘ui.router’]).config(function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise(‘admin’). $stateProvider.state(‘Name you pass in ui-sref’, { url: ‘path to url’, templateUrl: “filename” }); } |
$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
State | Route |
---|---|
A Place within App | A URL within App |
Nested Hierarchy | Flat Hierarchy |
Names are just names | Names are URLs |
Multiple Views(ui-view) | Single view (ng-view) |
Populate any view | Populate 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.
1 2 3 4 5 6 | <div ng-controller="parentcontroller"> <p>{{name}}</p> <p ng-controller="childcontroller">{{address}}</p> </div> |
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
1 2 3 | $StateProvider.state ('contacts.list', {}); |
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).
1 2 3 4 5 6 | $stateProvider.state ({ name: 'list', // state name can also be specified directly in the configuration parent: 'contacts' // parent route state name }); |
Here is a simple example of nested views.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | angular.module("mymodule") .config(function($httpProvider, $stateProvider, $urlRouterProvider) { $stateProvider.state('main', { templateUrl: 'templates/index.html' }) .state('main.inbox',{ url:'/inbox', views:{ 'myContainer':{ templateUrl:'templates/views/inbox.html' } } }) .state('main.outbox',{ url:'/outbox', views:{ 'myContainer':{ templateUrl:'templates/views/outbox.html' } } }) .state('main.compose',{ url:'/compose', views:{ 'myContainer':{ templateUrl:'templates/views/compose.html' } } }); // redirects to default route for undefined routes $urlRouterProvider.otherwise('/admin'); }); |
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:
1 2 3 4 5 6 7 | var contact = { name: ‘contact’, templateUrl : ‘contact.html’ controller:’...’ } |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | .state('parent',{ resolve:{ resA:function(){ return {'value':'A'} } } controller: function($scope,resA){ $scope.resA = resA.value; } }) .state(‘parent.child’,{ resolve: { resB: function(resA){ return {'value':resA.value = ‘B’} } } controller: function($scope,resA, resB){ $scope.resA2 =resA.value; $scope.resB2 = resB.value; } }); |
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.
1 2 3 4 5 6 7 8 | resolve: { 'contacts': ['contacts', function (contacts) { return contacts.all (); }] } |
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
1 2 3 4 | $state.go('destination.state'); <a ui-sref=""> |
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.
1 2 3 4 5 | .state('app',{ abstract:true, } |
$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.
1 2 3 | $stateProvider.state(‘beta.dashboard’{} |
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
1 2 3 | <div ui-view="main"></div> |
JS
angular-UI-router based on the state machine that provides routing and a series of nested functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | angular.module('myApp', ['ui.state']) .config(['$stateProvider', '$routeProvider', function ($stateProvider, $routeProvider) { $stateProvider .state('main', { abstract: true, url: '/main', views: { 'main': { template: '<h1>Hello!!!</h1>' + '<div ui-view="view1"></div>' + '<div ui-view="view2"></div>' } } }) .state('main.subs', { url: '', views: { 'view1@main': { template: "This is View1" }, 'view2@main': { template: "This is View2" } } }); }]) .run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; $state.transitionTo('main.subs'); }]); |
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?