ui-router for routes with ONLY SPECIFIC values

2019-05-11 02:19发布

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条回答
甜甜的少女心
2楼-- · 2019-05-11 03:16

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

查看更多
登录 后发表回答