In the following example i created a decorator
(runs only once per app at configuration phase) and adds an extra property to $state
service, so this approach does not add global variables to $rootscope
and does not require to add any extra dependency to other services than $state
.
In my example i needed to redirect a user to the index page when he was already signed in and when he was not to redirect him to the previous "protected" page after sign in.
The only unknown services (for you) that i use are authenticationFactory
and appSettings
:
authenticationFactory
just administrates the user login. In this case i use only a method to identify if the user is logged in or not.
appSettings
are constants just for not use strings everywhere. appSettings.states.login
and appSettings.states.register
contain the name of the state for the login and register url.
Then in any controller
/service
etc you need to inject $state
service and you can access current and previous url like this:
- Current:
$state.current.name
- Previous:
$state.previous.route.name
From the Chrome console:
var injector = angular.element(document.body).injector();
var $state = injector.get("$state");
$state.current.name;
$state.previous.route.name;
Implementation:
(I'm using angular-ui-router v0.2.17
and angularjs v1.4.9
)
(function(angular) {
"use strict";
function $stateDecorator($delegate, $injector, $rootScope, appSettings) {
function decorated$State() {
var $state = $delegate;
$state.previous = undefined;
$rootScope.$on("$stateChangeSuccess", function (ev, to, toParams, from, fromParams) {
$state.previous = { route: from, routeParams: fromParams }
});
$rootScope.$on("$stateChangeStart", function (event, toState/*, toParams, fromState, fromParams*/) {
var authenticationFactory = $injector.get("authenticationFactory");
if ((toState.name === appSettings.states.login || toState.name === appSettings.states.register) && authenticationFactory.isUserLoggedIn()) {
event.preventDefault();
$state.go(appSettings.states.index);
}
});
return $state;
}
return decorated$State();
}
$stateDecorator.$inject = ["$delegate", "$injector", "$rootScope", "appSettings"];
angular
.module("app.core")
.decorator("$state", $stateDecorator);
})(angular);