Angularjs: Simple injectable navigation service to facilitate redirecting to views in your application
September 4, 2014 Leave a comment
I am currently working on a proof of concept application that uses MVC Web API2 and a Client built using Angular.js. The project is still under development (you can find the most updated source code at: https://github.com/JinishBhardwaj/Online-Catalog). During the development of the client application i would usually want to redirect the user to another view. There were 2 basic use cases:
- Redirect a user to another view from the controller
- Redirect a user to another view after a time delay from a controller
In angular.js we can do the redirection with a time delay using two angular modules:
- $location
- $timeout
Essentially because the redirection functionality will be used in many controller I decided to write a simple angular service called the “navigationService” that can be simply injected as a dependency to any angular controller or another service instead of injecting the $location and $timeout modules on every occasion. Here is code for the service and its usage
'use strict'; var myApp = angular.module('angularApp', ['ngRoute']); myApp.factory('navigationService', ['$location', '$timeout', function ($location, $timeout) { var navigationServicefactory = {}; var _navigate = function (url, delay) { var timer = $timeout(function () { $timeout.cancel(timer); $location.path(url); }, delay); }; navigationServicefactory.navigate = _navigate; return navigationServicefactory; }]);
and then simply we can inject it to any controller and use it in this fashion:
'use strict'; myApp.controller('indexController', ['$scope', 'navigationService', 'authService', function ($scope, navigationService, authService) { $scope.authentication = authService.authentication; $scope.logout = function () { authService.logout(); navigationService.navigate('/index', 5000); }; }]);
where 5000 is time in milliseconds.
and that’s all!!