Angular UI Router: Different states with same URL?

前端 未结 2 339
长情又很酷
长情又很酷 2020-12-07 14:59

The landing page of my app has two states: home-public, home-logged-in. Now I want to show both states on the same URL, but let the controller and

相关标签:
2条回答
  • 2020-12-07 15:41

    I am not sure if two states can have the same url. What i can think can be a viable option would be to define a single state

    $stateProvider.state('home', {
      templateUrl: function (stateParams){
        // Implement a logic that select what view from the server should be returned for logged in user and otherwise
        //return 'templateurl';
      }
    })
    

    I have not tried but it should work.

    0 讨论(0)
  • 2020-12-07 15:48

    You could have a base state that controls which state to load, and you could simply have the child stated of that base state not have urls:

    .state('home', {
      url: "/home",
      templateUrl: "....",
      controller: function($scope,$state,authSvc) {
         if(authSvc.userIsLoggedIn()){
              $state.go('home.loggedin')
         }else{
              $state.go('home.public')
         }
      }
    })
    
    
    .state('home.public', {
      url: "",
      templateUrl: "....",
      controller: function($scope) {
         ...........
      }
    })
    
    .state('home.loggedin', {
      url: "",
      templateUrl: "....",
      controller: function($scope) {
         ...........
      }
    })
    

    Now in the controller of your base state (home) you can check if the user is logged in or not, and use $state.go() to load an appropriate state.

    EDIT

    As promised, a working plunk.

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