Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  176] [ 3]  / answers: 1 / hits: 22575  / 10 Years ago, sat, december 13, 2014, 12:00:00

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

More From » angularjs

 Answers
15

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
}
})

[#68492] Wednesday, December 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidengiancarlop

Total Points: 234
Total Questions: 115
Total Answers: 94

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;