Saqib Ali
Saqib Ali

Reputation: 12535

How to make AngularJS UI-router take, but ignore optional trailing backslash in URL?

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?

Upvotes: 1

Views: 771

Answers (1)

Sage
Sage

Reputation: 15408

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'
})

Upvotes: 1

Related Questions