mikek mikek - 1 year ago 157
AngularJS Question

AngularJS ui-router optional parameters

I tried to set up my routing like this

url: '/view/:inboxId?'

but Angular would throw this error:

Error: Invalid parameter name '' in pattern '/view/:inboxId?'

so basically I had to set up two different states:

state('view', {
url: '/view/:inboxId',
templateUrl: 'templates/view.html',
controller: 'viewCtrl'

state('view_root', {
url: '/view',
templateUrl: 'templates/view.html',
controller: 'viewCtrl'

Is there any way to combine these states into one?

Answer Source

To have an optional param - declare it as you did - but do not pass it. Here is an example. That all could work with one state (no root) or two (root and detail) as you like.

The definition mentioned in the question, is ready to handle these state calls:

// href
<a href="#/view/1">/view/1</a> - id is passed<br />
<a href="#/view/"> /view/ </a> - is is missing - OPTIONAL like <br />
<a href="#/view">  /view  </a> - url matching the view_root

// ui-sref
<a ui-sref="view({inboxId:2})">    - id is passed<br /> 
<a ui-sref="view">                 - is is missing - OPTIONAL like
<a ui-sref="view({inboxId:null})"> - id is explicit NULL <br />
<a ui-sref="view_root()">          - url matching the view_root

We do not have to use ? to mark parameter as optional. Just both url must be unique (e.g. /view/:id vs /view - where the second does not have trailing /)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download