1

I'm using AngularJS's UI-router to do routing. Currently, I have this:

  $stateProvider.state('mystate',
    {
      url: '/mystate/{id:int}/:slug/',
      params: {
        slug: {value: null, squash: true}
      },
      templateUrl: 'partials/mystate.html',
      controller: 'MyStateCtrl'
    }
  );

The id and optional slug URL parameters are captured iff there is a trailing backslash. If there is no trailing backslash, this pattern is not even matched. I need it to match with or without the trailing backslash in all cases. How can I do that?

I was told here to attach the following config on my app:

.config(['$urlMatcherFactoryProvider', function($urlMatcherFactoryProvider) {
      $urlMatcherFactoryProvider.strictMode(false);
    }
  ]
)

I did. But it still doesn't work without the trailing slashes. What should I do?

3
  • What if you removed the trailing slash from the pattern? Commented Jan 4, 2016 at 3:45
  • 1
    If you want an optional parameter, why don't you use query style parameters at the end of your route? You could encode them if the value is more than a simple string. Commented Jan 4, 2016 at 3:56
  • Harper, that worked. Commented Jan 4, 2016 at 4:16

1 Answer 1

1

Route parameters in UI Router are optional by default. That is why a trailing slash is needed. I can think of two solution to avoid the trailing slash if someone doesn't want to use query parameter approach:

  1. Setting up another route for the parameterless version.
  2. Using non url route parameters: that is omit the parameter you want to be optional and declare it in params attribute but in that case the optional parameter won't appear in the URL.

A sample code:

$stateProvider
.state('mystate', {
  url: '/mystate/{id:int}',
  params: {
    slug: {value: null, squash: true}
  },
  templateUrl: 'partials/mystate.html',
  controller: 'MyStateCtrl'
})
Sign up to request clarification or add additional context in comments.

1 Comment

Most of the time, we should focus on giving some explanation rather than posting a complete functional code. That is why my intention was to give an explanation rather than a code sample. the OP can easily pick yours one for better understanding if it helps

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.