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.

Should look later like:

Register a custom type that transforms the data. UI urlMatcherFactory Docs here:$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: