3

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

mrBorna
  • 1,757
  • 16
  • 16
  • define the route using the normal way `/:state/:city/:category` and then check for an accepted value in a resolve or in the controller. If any one of them is invalid, go to 404. – Kevin B May 27 '15 at 21:54

1 Answers1

3

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

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335