Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ui-router optional param without trailing slash

So this seems like a common problem but I haven't found any definite answer. Basically I have a state:

.state('users', {
     url: '/example/:id',
        templateUrl: 'angular-views/example.html',
        controller: 'ExampleCtrl'
    })

I want id to be optional.

Sure it matches

example/
example/1234

But it doesn't match without trailing slash.

example

I tried $urlMatcherFactoryProvider.strictMode(false);, but that does not seem to work for this case. I could use example?param=1234, but I prefer the cleaner version.

Do I really need to define a second state for this to work?

like image 862
Fredrik L Avatar asked Mar 03 '15 20:03

Fredrik L


1 Answers

You can define optional URL parameters by giving them a default value in the params object, like this. squash will hide the parameter in links if it's not defined.

.state('users', {
         url: '/example/:id',
            templateUrl: 'angular-views/example.html',
            controller: 'ExampleCtrl',
            params:  {
              id: {
                     value: null,
                     squash: true
                  }
                }
        });

I tried this locally and it seems to work OK regardless of trailing slash.

like image 114
Casey Avatar answered Oct 16 '22 03:10

Casey