UI Router conditional ui views?

后端 未结 9 1167
遥遥无期
遥遥无期 2021-01-30 21:23

I can\'t figure out a reasonable way, which doesn\'t feel like a hack, to solve this rather trivial problem.

I want a guest to see a splash page when they access the ind

相关标签:
9条回答
  • 2021-01-30 21:35

    Anywhere (probably in some high-level controller) you should be able to just bind a '$routeChangeStart' event to the $rootScope and do your check then:

    $rootScope.$on('$routeChangeStart', function(next, current){
        if(next != '/login' && !userLoggedIn){
            $location.path( "/login" );
        }
    });
    

    This will get fired every time a new route is set, even on the first visit to the page.

    0 讨论(0)
  • 2021-01-30 21:38

    If I understand the question; you want to make sure that the user who hasn't logged in cannot see a page that requires log in. Is that correct?

    I've done so with code like this inside a controller:

    if(!'some condition that determines if user has access to a page'){
     $location.path( "/login" );
    }
    
    0 讨论(0)
  • 2021-01-30 21:40

    The templateUrl can be a function as well so you can check the logged in status and return a different view and define the controller in the view rather than as part of the state configuration

    0 讨论(0)
  • 2021-01-30 21:45

    The way I've done this is pretty simple. I made one for our A/B testing strategy. This is the gist:

    resolve: {
       swapTemplate: function(service) {
          // all of this logic is in a service
          if (inAbTest) {
             this.self.templateUrl = '/new/template.html';
          }
       }
       ... other resolves
    }
    

    This gets called before the template is downloaded and therefor you're allowed to swap out the template url.

    0 讨论(0)
  • 2021-01-30 21:47

    If you're using UI Router, just create three states: the root state, with the '/' URL, and two direct descendant states with no URLs. In the onEnter of the root state, you detect the state of the user and transition to the correct child state accordingly. This gives the appearance of keeping the same URL for both child states, but allows you to have to separate states with separate configurations.

    0 讨论(0)
  • 2021-01-30 21:47

    My Solution:

    angular.module('myApp')
    .config(function ($stateProvider) {
        $stateProvider
            .state('main', {
                url: '/',
                controller: function (Auth, $state) {
                    if (someCondition) {
                        $state.go('state1');
                    } else {
                        $state.go('state2');
                    }
                }
            });
    });
    

    where state 1 and state 2 are defined elsewhere.

    0 讨论(0)
提交回复
热议问题