Javascript 带有角度 ui-router 的多个可选参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27464625/
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
Multiple optional parameters with angular ui-router
提问by Mehmet Ata?
I am trying to use multiple optional parameters with ui-router but it does not seem to work. Below are the tests i did:
我试图在 ui-router 中使用多个可选参数,但它似乎不起作用。以下是我所做的测试:
Single parameter is OK
单参数OK
state.url url called state param values
/page/:x /page/ $stateParams.x == ""
/page/:x /page/2 $stateParams.x == "2"
One optional parameter is OK
一个可选参数就可以了
/page/:x? /page/ $stateParams.x == ""
/page/:x? /page/2 $stateParams.x == "2"
Two parameters are OK (except the ugly double slashes in first case, /pageand /page/turn into /page//. But since the parameters are not optional that's OK)
两个参数都OK了(除了在第一种情况下丑陋的双斜线,/page并/page/转成/page//,但由于参数不可选这是确定)
/page/:x/:y /page// $stateParams.x == "" && $stateParams.y == ""
/page/:x/:y /page/2 $stateParams.x == "" && $stateParams.y == ""
/page/:x/:y /page/2/ $stateParams.x == "2" && $stateParams.y == ""
/page/:x/:y /page/2/3 $stateParams.x == "2" && $stateParams.y == "3"
Two optional parameters behaves strange. Second parameters is always undefined and it cannot solve first parameter when I specify the second one.
两个可选参数的行为很奇怪。第二个参数始终未定义,当我指定第二个参数时,它无法解决第一个参数。
/page/:x?/:y? /page/ $stateParams.x == "" && $stateParams.y == undefined
/page/:x?/:y? /page/2 $stateParams.x == "2" && $stateParams.y == undefined
/page/:x?/:y? /page/2/ $stateParams.x == "" && $stateParams.y == undefined
/page/:x?/:y? /page/2/3 $stateParams.x == "" && $stateParams.y == undefined
回答by Chris T
UI-Router optional parameter are not specified by modifying the URL. Rather, they are specified using the paramsobject in the state definition.
UI-Router 可选参数不是通过修改 URL 来指定的。相反,它们是使用params状态定义中的对象指定的。
The declaration url: '/page/:x?/:y?'does not mark x and y as optional parameters. Instead, the question mark is used to separate the URL and Query Param portion of the URL.
该声明url: '/page/:x?/:y?'没有将 x 和 y 标记为可选参数。相反,问号用于分隔 URL 和 URL 的查询参数部分。
Read the description text in the UrlMatcherdocs and the $stateProvider.statedocs for url, then for params.
阅读UrlMatcher文档和$stateProvider.state文档中的描述文本for url,然后 for params。
You will end up with optional params configured like so:
您最终将获得如下配置的可选参数:
$stateProvider.state('page', {
url: '/page/:x/:y',
params: {
x: 5, // default value of x is 5
y: 100 // default value of y is 100
}
})

