AngularJS UI-Router URL renaming / beautify ui-sref

Veröffentlicht von

For making URLs nicer, it’s possible to write your own beautifier with intercepting the AngularJS ui-router.
In my case, I wanted to get rid of the spaces and replace them by dashes.

Default: 
http://localhost/detail/My%20Product%20Name/123456789/
Should look later like:
http://localhost/detail/My-Product-Name/123456789/

Register a custom type that transforms the data. UI urlMatcherFactory Docs here: http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.$urlMatcherFactory
Define a custom type. Implement encode, decode, is and pattern and register it via $urlMatcherFactory:

app.config(function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) {
// Product detail URL Rewrite
            var productNameRename = {
                encode: function(str) { return str && str.replace(/ /g, "-"); },
                decode: function(str) { return str && str.replace(/-/g, " "); },
                is: angular.isString,
                pattern: /[^/]+/
            };
            $urlMatcherFactoryProvider.type('productName', productNameRename);
angularjs ui-router:
.state('base.product.detail', {
    url: 'detail/{productName:productName}/:productId/',

In the template I’m using the productRename as the target: