简体   繁体   中英

$state changes but the view don't - AngularJS

I have this config for my states:

$stateProvider
    .state('login', {
        url: '/login',
        templateUrl: 'scripts/login/login.tpl.html',
        controller: 'LoginController',
        access: 'public'
    })
    .state('recovery', {
        url: '/recovery',
        templateUrl: 'scripts/recovery/recovery.tpl.html',
        controller: 'RecoveryController',
        access: 'public'
    })
    .state('/', {
        url: '/',
        templateUrl: 'scripts/home/home.tpl.html',
        access: 'private'
    });

I have this event when the state changes:

$scope.$on('$stateChangeStart', function (event, toState) {
    // redirect to login
    if(toState.access === 'private' && !AuthService.isLoggedIn()) {
        // User needs to login
        console.log('-> need login');
        $location.path('/login');
    }
}

The problem is: When I enter in application, it shows '/#/login' in URL and login view. If i go in url address and remove the '/login' (/#/) and then press enter, the home view shows, but in console I can see the '-> need login' and in the url shows '/#/login'.

I don't know what's going on, but the $location.path doesn't work to redirect back to '/#/login' with login view.

I found a solution for my problem.

I switch the $location.path for $state.go and i added event.preventDefault above the $state.go call.

Now is working great! =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM