javascript Angular UI 路由器:具有相同 URL 的不同状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23344055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular UI Router: Different states with same URL?
提问by jvannistelrooy
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 template depend on the user session (is the user logged in or not?).
我的应用程序的登录页面有两种状态:home-public
, home-logged-in
。现在我想在同一个 URL 上显示两种状态,但让控制器和模板取决于用户会话(用户是否登录?)。
Is there a way to achieve this?
有没有办法实现这一目标?
回答by Mohammad Sepahvand
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.
现在在您的基本状态 ( home
)的控制器中,您可以检查用户是否已登录,并用于$state.go()
加载适当的状态。
EDIT
编辑
As promised, a working plunk.
正如所承诺的那样,一个工作 plunk。
回答by Chandermani
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
我不确定两个州是否可以拥有相同的url
. 我认为可以是一个可行的选择是定义一个单一的状态
$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.
我还没有尝试过,但它应该可以工作。