Handling trailing slashes in angularUI router

As of ui-router version 0.2.11 you can do this:

$urlMatcherFactoryProvider.strictMode(false);

This will treat URLs with and without trailing slashes identically.


I don't have enough rep for a comment so making an answer :-

$urlMatcherFactoryProvider.strictMode(false);

Needs to be before the $stateProvider.state part.


There is a link to working plunker

And this is the updated rule definition:

  $urlRouterProvider.rule(function($injector, $location) {

    var path = $location.path();
    var hasTrailingSlash = path[path.length-1] === '/';

    if(hasTrailingSlash) {

      //if last charcter is a slash, return the same url without the slash  
      var newPath = path.substr(0, path.length - 1); 
      return newPath; 
    } 

  });

And these links will now work properly:

  <ul class="nav">
    <li><a ui-sref="route1">Route 1</a></li>
    <li><a ui-sref="route2">Route 2</a></li>
    <li><a href="#/route1/">#/route1/</a></li>
    <li><a href="#/route2/">#/route2/</a></li>
    <li><a href="#/route1" >#/route1</a></li>
    <li><a href="#/route2" >#/route2</a></li>
  </ul>

The magic could be defined like this: do return changed value if there is a change... otherwise do nothing... see example