问题描述
所以这似乎是一个常见问题,但我还没有找到确切的答案.基本上我有一个状态:
So this seems like a common problem but I haven't found any definite answer.Basically I have a state:
.state('users', {
url: '/example/:id',
templateUrl: 'angular-views/example.html',
controller: 'ExampleCtrl'
})
我希望id是可选的.
I want id to be optional.
确定匹配
example/
example/1234
但是,如果没有斜杠,它就不匹配.
But it doesn't match without trailing slash.
example
我尝试了$urlMatcherFactoryProvider.strictMode(false);
,但是在这种情况下似乎不起作用.我可以使用example?param=1234
,但是我更喜欢清洁的版本.
I tried $urlMatcherFactoryProvider.strictMode(false);
, but that does not seem to work for this case. I could use example?param=1234
, but I prefer the cleaner version.
我真的需要定义第二种状态才能工作吗?
Do I really need to define a second state for this to work?
推荐答案
您可以通过在params
对象中为它们提供默认值来定义可选的URL参数,如下所示. squash
将在链接中隐藏该参数(如果未定义).
You can define optional URL parameters by giving them a default value in the params
object, like this. squash
will hide the parameter in links if it's not defined.
.state('users', {
url: '/example/:id',
templateUrl: 'angular-views/example.html',
controller: 'ExampleCtrl',
params: {
id: {
value: null,
squash: true
}
}
});
我在本地尝试过此方法,无论后跟斜杠,它似乎都可以正常工作.
I tried this locally and it seems to work OK regardless of trailing slash.
这篇关于ui-router可选参数,不带斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!