jhummel
jhummel

Reputation: 1764

UI-Router optional url parameter preceeding static part

I'm using the 1.x version of UI-Router. I have a site that is broken up by location, each location has identical layouts and content for its pages:

mysite.com
mysite.com/location1
mysite.com/location1/about
mysite.com/location1/contact

mysite.com/location2
mysite.com/location2/about
mysite.com/location2/contact

I'd like to use the same templates/components for the pages (about, contact) etc, but change the API queries I make based on the parameter. I'm setting up my states with a location URL parameter like so:

.state('about', {
    url: '/:location/about',
    params: {
      location: 'default'
    }
})

What I'd really like to be able to do is instead of providing some sort of default location parameter, I'd like it to be completely optional - as in the following urls would work:

mysite.com/about
mysite.com/contact

And it would provide the default (but not show in the URL). I'd like the other directives like ui-sref to work the same way. I should be able to use:

ui-sref="about({location: something})"

and if something was null or falsy it would show the shortened url. Other directives like ui-sref-active should be smart enough to recognize the defaults as well.

Something like that possible? Thanks in advance!

Upvotes: 1

Views: 541

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

There is a more detailed description:

Angular js - route-ui add default parmeter

The point is - the parameter must be precisely defined, to make it clear for UI-Router to decide: "Is it parameter? or is it next part (e.g. /about)"

A snippet from the above link:

.state('root', {
    url: '/{lang:(?:en|he|cs)}',
    abstract: true,
    template: '<div ui-view=""></div>',
    params: {lang : { squash : true, value: 'en' }}
})

so, values of lang parameter are easy to distinguish for UI-Router from other values. Some more magic is added with squash option. see more here

Upvotes: 1

Related Questions