7
down vote
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 ===...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.