Skip to content

Instantly share code, notes, and snippets.

@deanapeterson
Last active August 29, 2015 14:13
Show Gist options
  • Save deanapeterson/5b28204e9aadb225015a to your computer and use it in GitHub Desktop.
Save deanapeterson/5b28204e9aadb225015a to your computer and use it in GitHub Desktop.
Alternate way to bind to UI-Router events
/**
* Similar to the idea of adding 'rules' to a states data object, I add injectible
* handlers keyed to the specific stateChange relationship:
*
* 'onToStateChangeStart/Success' - fired when the state is the destination
* 'onFromStateChangeStart/Success' - fired when the state is the previous
*
* I like this because the we can run all handlers through one event binding
* and make the state definition object for self-contained.
**/
angular.module("app", ["ui.router"])
.config(function(){
$stateProvider
.state("root", {
template : "<div ui-view></div>",
data : {
//fired only when state is the "to" state
onToStateChangeStart : function(to, from){
},
//fired only when state is the "from" state
onFromStateChangeStart : function(event, $state, toState){
if($state.includes(toState) === false){
event.preventDefault();
}
}
}
});
})
.run(function($rootScope, $injector){
$rootScope.$on("$stateChangeSuccess", function(event, toState, toParams, fromState, fromParams){
var stateChangeArgs = {
event : event,
toState : toState,
toParams : toParams,
fromState : fromState,
fromParams : fromParams
};
var toStateData = toState.data || {};
var fromStateData = fromState.data || {};
if(toStateData.onToStateChangeStart){
$injector.invoke(toStateData.onToStateChangeStart, {}, stateChangeArgs);
}
if(fromStateData.onFromStateChangeStart){
$injector.invoke(fromStateData.onFromStateChangeStart, {}, stateChangeArgs);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment