Multiple optional route parameters and pretty urls with Angular ui router

时间:2016-07-11 21:49:02

标签: angularjs angular-ui-router optional-parameters

I am trying to use multiple optional parameters to make urls looks like

/:region/:direction/:subdirection/page/

where all params instead of the last one are optional.

I've tried to use

params:{region: {value: 'default', squash:true}, ...}

for each optional parameter, but when some of them are missed in url, the router doesn't work.

So, the only solution I've found in order to save pretty urls in this situation is to declare multiple routes:

.state('page', {
    url: '/:region/page'
}
.state('page-direction', {
    url: '/:region/:direction/page'
}
.state('page-subdirection', {
    url: '/:region/:direction/:subdirection/page'
}

Additionally: 1. there will be no subdirection without direction, 2. region will be in every link, but it is variable

Are there any optional solutions? Thnx!

2 个答案:

答案 0 :(得分:0)

The default parameters are for internal routing, example

$state.go('page-subdirection');

The above will redirect to the state and the $stateParams.region will be the default value you defined for that state.

While $state.go('page-subdirection', {region: 'newValue'); will make $stateParams.region to be newValue in that specific case.

The same apply for constructing the URL from the view:

<a ui-sref="page-subdirection">
<a ui-sref="page-subdirection({region: 'newValue'})">

答案 1 :(得分:0)

It may also depend on what your final goal is. From what you're describing, it seems that you may actually be trying to pass in filters into a single state, not necessarily trying to route to 3 different states.

If in the case of filtering a single state, I'd recommend using query parameters as described in the docs (https://github.com/angular-ui/ui-router/wiki/URL-Routing). The advantage is that query parameters are not required or used from a routing point of view, they're simply parameters that your controller will utilize to filter data or tweak the view.

Snippet from above doc link:

Query Parameters

You can also specify parameters as query parameters, following a '?':

url: "/contacts?myParam" // will match to url of "/contacts?myParam=value"

If you need to have more than one, separate them with an '&':

url: "/contacts?myParam1&myParam2" // will match to url of "/contacts?myParam1=value1&myParam2=wowcool"