0

I am trying to define a single state with an optional integer route parameter.

I have defined the following state in my application

$stateProvider.state('configuration', {
  stateUrl: '/configuration/{id:int}',
  template: '<div></div>'
});

This is working for all routes that have an id e.g. /configuration/1, but it does not work for routes without the id e.g. /configuration/.

If I drop the type definition, like the below, then routes work with or without the id at the end but I end up with a string id rather than a number.

$stateProvider.state('configuration', {
  stateUrl: '/configuration/:id',
  template: '<div></div>'
});

Is it possible to define an optional typed route parameter?

2 Answers 2

1

I managed to get this working by using the params option.

$stateProvider.state('configuration', {
  stateUrl: '/configuration/{id:int}',
  params: { id: { value: null, squash: true } },
  template: '<div></div>'
});
Sign up to request clarification or add additional context in comments.

Comments

0

You can make parameter optional using '?'

Please try following

$stateProvider.state('configuration', {
    stateUrl: '/configuration/:id?',
    template: '<div></div>'
});

5 Comments

But then I would lose the type definition and it would become a string right?
Yes you will lose definition. It will accept string also. When ever we use braces '{}' in route parameter we are not allow to use parameter as optional or greedy. This link may help you -- github.com/angular-ui/ui-router/wiki/URL-Routing
Thanks, but I was after an optional integer parameter. Is there no way to do this? Where in the ui-router docs does it say that {} treats parameters differently to :?
I tried same at my end but couldn't succeed. To resolve current situation, create two different Routes Url: '/configuration/{id:int}' and Url: '/configuration/' pointing to same template,controllers and other options. In doc-- it is stated for regex. Regex required {} braces. After watching this I made my above comment. :) Statement from Doc:-Route parameters with regular expressions can't be optional or greedy
Thanks again. I also appear to have had success with params object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.