Created
December 11, 2013 14:52
-
-
Save pechorin/7911719 to your computer and use it in GitHub Desktop.
ui-router state constraints example
This file contains hidden or 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
// Protection for ui-router states | |
// | |
// usage: | |
// | |
// app.run(function($stateConstraints) { | |
// | |
// $stateConstraints.protect({ | |
// state : 'myState', | |
// guard : function($currentUser) { // <- any service | |
// // guard should return FALSE if transition to state should be cancelled | |
// if ($currentUser.isSignedOut()) return false | |
// }; | |
// onFail: function() { | |
// alert("Signed users only"); | |
// } | |
// }); | |
// | |
// }) | |
angular.module('app.services').service('$stateConstraints', function($injector, $rootScope) { | |
var service = this; | |
// list of all available guards | |
this.guards = { | |
signedEmployerOnly : function($currentSession, $state) { | |
if ($currentSession.isSignedIn() && $currentSession.user.isEmployer()) { | |
return true; | |
} else { | |
$state.go('default'); | |
return false; | |
} | |
}, | |
signedEmployerOwnerOnly : function($currentSession, $state, $stateParams) { | |
if (service.guards.signedEmployerOnly($currentSession, $state)) { | |
// TODO: check state params here | |
return true; | |
} else { | |
return false; | |
} | |
}, | |
signedOutOnly : function($currentSession) { | |
return $currentSession.isSignedOut() == true; | |
} | |
} | |
// options -> { | |
// guard: guardFunction, | |
// state: 'stateName' | |
// } | |
this.protect = function protect(options) { | |
$rootScope.$on('$stateChangeStart', function(event, toState, toParams) { | |
if ( toState.name != options.state ) return; | |
var guardResult = $injector.invoke(options.guard, undefined, { toParams: toParams, toState: toState }); | |
if (guardResult == false) { | |
event.preventDefault(); | |
if ( _.isFunction(options.onFail) ) { | |
$injector.invoke(options.onFail); | |
} else { | |
$injector.invoke(function($state) { | |
console.log("request to " + toState.name + " declined with guard"); | |
$state.go('default'); | |
}); | |
} | |
} | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage example: