Last active
November 25, 2016 07:33
-
-
Save deanapeterson/b93b48fd8c258861f26b to your computer and use it in GitHub Desktop.
Adding "$stateChangeRejected" event to ui-router.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
"use strict"; | |
/** | |
* Hijacks the ui-router $state.transitionTo() method to capture it's promise. | |
* the promise is added to the $state as $promise (may or may not be needed); | |
* also adds handler for rejection of the $promise. | |
*/ | |
angular | |
.module("stm.ui.stateChangeRejected", ['ui.router']) | |
.config(stateChangeRejected); | |
function stateChangeRejected($provide){ | |
$provide.decorator("$state", decorateTransitionTo); | |
decorateTransitionTo.$inject = ['$delegate', '$rootScope']; | |
function decorateTransitionTo($delegate, $rootScope){ //$delegate === $state | |
var nativeTransitionTo = $delegate.transitionTo; //transfer reference | |
$delegate.transitionTo = transitionToWrapper;// replace with wrapper | |
return $delegate; | |
function transitionToWrapper(){ | |
var args = [].slice.call(arguments); | |
var promise = nativeTransitionTo.apply(this, args);//call original transitionTo, capture promise | |
promise['catch'](onStateRejection); //add handler for rejection | |
$delegate.$promise = promise; //add $promise to default $state object | |
return promise; | |
function onStateRejection(error){ | |
var toState = $delegate.get(args[0]); | |
var toParams = args[1]; | |
$rootScope.$broadcast("$stateChangeRejected", toState, toParams, $delegate.current, $delegate.params, error); | |
return error; | |
} | |
} | |
} | |
} | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bogdanalexe90, I'm gonna take a look at that. Thanks