ui-router for routes with ONLY SPECIFIC values

随声附和 提交于 2019-12-22 10:29:28

问题


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 city = /los-angeles|san-francisco|.../i category = /painting|plumbing|.../i

These lists are long so having a huge regex doesn't make much sense (or does it?)

Would I use a rule() ? $urlMatcherFactory? how can I use a function?

any help is appreciated. Thanks in advance


回答1:


The way to go here, is with custom type.

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}
    ...

That all could work because we can define url for UrlMatcher like this

'{' 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.

So, not only regexp - but also the type - including our custom one



来源:https://stackoverflow.com/questions/30493625/ui-router-for-routes-with-only-specific-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!