I'm writing a handler for $stateChangeStart
:
var stateChangeStartHandler = function(e, toState, toParams, fromState, fromParams) {
if (toState.includes('internal') && !$cookies.MySession) {
e.preventDefault();
// Some login stuff.
}
};
$rootScope.$on('$stateChangeStart', stateChangeStartHandler);
toState
does not have the includes method. Should I be doing something different, or is there a way to do what I'm trying to do?
Also, when //some login stuff includes a $state.go(...)
, I get an infinite loop. What might cause that?
Here's a more complete example demonstrating what we eventually got to work:
angular.module('test', ['ui.router', 'ngCookies'])
.config(['$stateProvider', '$cookiesProvider', function($stateProvider, $cookiesProvider) {
$stateProvider
.state('public', {
abstract: true
})
.state('public.login', {
url: '/login'
})
.state('tool', {
abstract: true
})
.state('tool.suggestions', {
url: '/suggestions'
});
}])
.run(['$state', '$cookies', '$rootScope', function($state, $cookies, $rootScope) {
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.name.indexOf('tool') > -1 && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.name.indexOf('public') > -1 && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
});
I don't like using indexOf
to search for a particular state in the toState
. It feels naive. I'm not sure why toState
and fromState
couldn't be an instance of the $state
service, or why the $state
service couldn't accept a state configuration override in its methods.
The infinite looping was caused by a mistake on our part. I don't love this, so I'm still looking for better answers.
Suggestion 1
When you add an object to
$stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.Example route configuration
The
$stateChangeStart
event gives you acces to thetoState
andfromState
objects. These state objects will contain the configuration properties.Example check for the custom module property
I didn't change the logic of the cookies because I think that is out of scope for your question.
Suggestion 2
You can create a Helper to get you this to work more modular.
Value
publicStates
Value
privateStates
The Helper
Now you can use the helper to add the state configuration to your state configuration.
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested