Millenjo
Millenjo

Reputation: 441

ui-sref-active problems with parent state redirection

This might be a dupe but I haven't found an answer that solves my problem exactly.

Lets say that I have 3 states.

account
account.settings
account.users

I want a link to be active on both childstates so I have a link like so

<a ui-sref="account" ui-sref-active="active">

And when i click this link, I want to redirect to the account.settings state. So I add a redirect in "onEnter", but that only triggers the first time I click the link. So I click the link and get redirected to the account.settings state, but if I click it again, onEnter doesn't trigger so i get flung to the account state, which is not what I want.

I've tried adding the logic in a state controller instead with the same result, I've also tried to use the $urlRouterProvider.when() function to redirect but I've run in to similar problems with that approach.

I feel as to I'm missing a point somewhere and I should have "gotcha" moment but I've been struggling with this a few days now and I can't seem to get it.

Upvotes: 0

Views: 270

Answers (1)

cristiano2lopes
cristiano2lopes

Reputation: 3498

If you want to pursuit the redirection solution you should probably do it in the $stateChangeStart event. Something like:

$rootScope.$on('$stateChangeStart', function(event, toState, fromState){
    if (toState.name === 'account' &&
        (fromState.name === 'account.settings' || fromState.name === 'account.users')){
        event.preventDefault();
        $state.transitionTo('account.settings');
    }
});

But you can always sref to the correct account.settings and use the ngClass binded to a function in the scope that decides if the link should be active, and avoid the redirection.

Upvotes: 1

Related Questions