Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
luiquao Avatar asked Aug 24 '14 22:08

luiquao


1 Answers

The code below allows for truly optional parameters, if you don't mind having a couple extra states.

I turned my original state into an abstract one by adding the abstract attribute, and then created two children states, one with a url that has params, one with a blank url that references the parent.

It works well on my dev site, and doesn't require a trailing slash, in fact, if you want the trailing slash, you'll have to add a state/when for it.

  .state('myState.search', {
    url:'/search',
    templateUrl: urlRoot + 'components/search/search.view.html',
    controller: 'searchCtrl',
    controllerAs: 'search',
    abstract: true,
  })
  .state('myState.search.withParams', {
    url:'/:type/:field/:operator/:value',
    controller: 'searchCtrl',//copy controller so $stateParams receives the params
    controllerAs: 'search'
  })
  .state('myState.search.noParams', {
    url:''
  });
like image 71
SethWhite Avatar answered Oct 05 '22 05:10

SethWhite