ui-router 用于只有特定值的路由 [英] ui-router for routes with ONLY SPECIFIC values
问题描述
我正在尝试为具有以下结构的多个唯一登录页面构建路由
I'm trying to build a route for multiple unique landing pages with the following structure
domain.com/:state/:city/:category
如何定义路线,以便州、城市和类别只能是预定义值之一,也就是:
How can I define the route so that the state, city, and category can be only one of predefined values, aka:
state =/ca|ma|ak|az|ar .../i城市 =/洛杉矶|旧金山|.../icategory =/painting|plumbing|.../i
这些列表很长,所以拥有一个巨大的正则表达式没有多大意义(或者是吗?)
These lists are long so having a huge regex doesn't make much sense (or does it?)
我会使用 rule() 吗?$urlMatcherFactory?如何使用函数?
Would I use a rule() ? $urlMatcherFactory? how can I use a function?
感谢任何帮助.提前致谢
any help is appreciated. Thanks in advance
推荐答案
这里的方法是使用自定义类型.
The way to go here, is with custom type.
如本Q &A,以防我们想创建一些准备处理值的类型true、false、1、0为boolean
,我们可以这样定义(有也是工作 plunker):
As shown in this Q & A, in case we wan to create some type which is ready to process values true, false, 1, 0 as boolean
, we can define it like this (there is also working plunker):
app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactoryProvider) {
$urlMatcherFactoryProvider.type('boolean',
// our type custom type
{
name : 'boolean',
decode: function(val) { return val == true ? true : val == "true" ? true : false },
encode: function(val) { return val ? 1 : 0; },
equals: function(a, b) { return this.is(a) && a === b; },
is: function(val) { return [true,false,0,1].indexOf(val) >= 0 },
pattern: /bool|true|0|1/
})
}]);
我们可以用同样的方式定义我们的类型
The same way we can define our types
$urlMatcherFactoryProvider.type('state' , ...
$urlMatcherFactoryProvider.type('city' , ...
$urlMatcherFactoryProvider.type('category', ...
然后我们可以将它们用于任意数量的状态定义:
And later we can use them for any amount of state defintions:
...
.state('mystate', {
url: 'xxx/{state:state}/{city:city/{category:category}
...
这一切都可以工作,因为我们可以为 UrlMatcher 像这样
That all could work because we can define url for UrlMatcher like this
'{' name ':' regexp|type '}'
- 带有正则表达式或类型名称的卷曲占位符.如果正则表达式本身包含花括号,它们必须成对匹配或用反斜杠转义.
'{' name ':' regexp|type '}'
- curly placeholder with regexp or type name. Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.
所以,不仅是正则表达式 - 还有 type
- 包括我们自定义的
So, not only regexp - but also the type
- including our custom one
这篇关于ui-router 用于只有特定值的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!