Igor Simic
7 years ago

Angular ui-router replacing slash with %2F - quick fix


If you have a forwarded slash in your ui-sref link, it could happen that it is encoded by ui-router to `%2F`. Which can not be appreciated in some cases because it look not so good from SEO perspective (i guess) and definitely does not look nice in your URL.

For example if you have link like this:
<a ui-sref="content({slug:'hello-world/'})">Hello world</a>
....
// and your stateProvider looks like this
$stateProvider
     .state('content',{
       url: '/:slug',
       ...

      })

 most likely it will be translated in URL to something like this:
hello-world~2F
// or
hello-world%2F
Which does not look so nice.

To fix this issue we have to disable encoding parameters in angular ui-router by using param raw:true, but this option is only available in ui-router version 1.0 (at the moment of writing this article is in RC version ) which can be found here:
https://cdnjs.com/libraries/angular-ui-router/1.0.0-rc.1

To make this work we need to update $urlMatcherFactoryProvider before we set the $stateProvider:
$urlMatcherFactoryProvider.type('SlashFix', {
      raw:    true,
    });

// and then use the SlashFix to encode slug param
$stateProvider
      .state('content',{
       url: '/{slug:SlashFix}'
       ...

      })
and voila, your URL links look good again :)