19

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

1 Answer 1

30

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
  }
})
Sign up to request clarification or add additional context in comments.

4 Comments

This is a good answer simply for not just saying to use query parameters like I expected people would.
For me, it pops a "Error: Both params and url specicified in state 'page'" error.
And when I read this error, I think: "Error: 'ci' specified twice in 'specicified' ". (your_lol_here)
Make sure you're using a recent version of ui router

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.