20

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?

thomaux
  • 19,133
  • 10
  • 76
  • 103
Fredrik L
  • 1,790
  • 4
  • 21
  • 28

1 Answers1

42

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.

Casey
  • 3,307
  • 1
  • 26
  • 41
  • Does not work for me. Plz See the demo https://plnkr.co/edit/3aBchxk2nu6FiDrV3WNN?p=preview ... I used that squash but still Post 1 works fine because of trailing slashes but Post 2 does not work at all – Sami Dec 28 '16 at 15:34
  • @Sami I'm not sure this will work with multiple squashable params. – Casey Dec 28 '16 at 15:49
  • But its not working for even single params when using `href` instead of `state`. Plz see https://plnkr.co/edit/3aBchxk2nu6FiDrV3WNN?p=preview – Sami Dec 28 '16 at 16:37
  • @Sami I'd recommend posting a separate question. I'm not exactly sure what your problem is and I'm not really able to spend too much time looking right now. – Casey Dec 28 '16 at 17:52
  • No problem dear. Yes I already have a separate question. http://stackoverflow.com/questions/39082825/angular-url-without-slash-with-optional-parameters – Sami Dec 28 '16 at 17:59