AngularJS ui-router 可选参数 [英] AngularJS ui-router optional parameters
问题描述
我试着像这样设置我的路由
I tried to set up my routing like this
...
url: '/view/:inboxId?'
...
但是 Angular 会抛出这个错误:
but Angular would throw this error:
Error: Invalid parameter name '' in pattern '/view/:inboxId?'
所以基本上我必须设置两个不同的状态:
so basically I had to set up two different states:
state('view', {
url: '/view/:inboxId',
templateUrl: 'templates/view.html',
controller: 'viewCtrl'
}).
state('view_root', {
url: '/view',
templateUrl: 'templates/view.html',
controller: 'viewCtrl'
})
有没有办法将这些状态合二为一?
Is there any way to combine these states into one?
推荐答案
要有一个可选参数 - 像你一样声明它 - 但不要传递它.这是一个示例.所有这些都可以根据您的喜好使用一种状态(无根) 或两种(根和详细信息).
To have an optional param - declare it as you did - but do not pass it. Here is an example. That all could work with one state (no root) or two (root and detail) as you like.
问题中提到的定义,已准备好处理这些状态调用:
The definition mentioned in the question, is ready to handle these state calls:
// href
<a href="#/view/1">/view/1</a> - id is passed<br />
<a href="#/view/"> /view/ </a> - is is missing - OPTIONAL like <br />
<a href="#/view"> /view </a> - url matching the view_root
// ui-sref
<a ui-sref="view({inboxId:2})"> - id is passed<br />
<a ui-sref="view"> - is is missing - OPTIONAL like
<a ui-sref="view({inboxId:null})"> - id is explicit NULL <br />
<a ui-sref="view_root()"> - url matching the view_root
我们不必使用 ?
将参数标记为可选.只是两个 url 必须是唯一的(例如 /view/:id
与 /view
- 其中第二个没有尾随 /
)
We do not have to use ?
to mark parameter as optional. Just both url must be unique (e.g. /view/:id
vs /view
- where the second does not have trailing /
)
这篇关于AngularJS ui-router 可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!