I am trying to use multiple optional parameters with ui-router but it does not seem to work. Below are the tests i did:
Single parameter is OK
state.url url called state param values
/page/:x /page/ $stateParams.x == ""
/page/:x /page/2 $stateParams.x == "2"
One optional parameter is OK
/page/:x? /page/ $stateParams.x == ""
/page/:x? /page/2 $stateParams.x == "2"
Two parameters are OK (except the ugly double slashes in first case, /page
and /page/
turn into /page//
. But since the parameters are not optional that's OK)
/page/:x/:y /page// $stateParams.x == "" && $stateParams.y == ""
/page/:x/:y /page/2 $stateParams.x == "" && $stateParams.y == ""
/page/:x/:y /page/2/ $stateParams.x == "2" && $stateParams.y == ""
/page/:x/:y /page/2/3 $stateParams.x == "2" && $stateParams.y == "3"
Two optional parameters behaves strange. Second parameters is always undefined and it cannot solve first parameter when I specify the second one.
/page/:x?/:y? /page/ $stateParams.x == "" && $stateParams.y == undefined
/page/:x?/:y? /page/2 $stateParams.x == "2" && $stateParams.y == undefined
/page/:x?/:y? /page/2/ $stateParams.x == "" && $stateParams.y == undefined
/page/:x?/:y? /page/2/3 $stateParams.x == "" && $stateParams.y == undefined
UI-Router optional parameter are not specified by modifying the URL. Rather, they are specified using the params
object in the state definition.
The declaration url: '/page/:x?/:y?'
does not mark x and y as optional parameters. Instead, the question mark is used to separate the URL and Query Param portion of the URL.
Read the description text in the UrlMatcher docs and the $stateProvider.state docs for url
, then for params
.
You will end up with optional params configured like so:
$stateProvider.state('page', {
url: '/page/:x/:y',
params: {
x: 5, // default value of x is 5
y: 100 // default value of y is 100
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With