Angular ui.router ui-sref replace url characters - decorate

I am looking for an opportunity to replace characters in ui-sref by observing the target url.

.state('base.product.detail', { url: 'detail/:productName-:productId/' 

The urls now look like this:

 Now: http://localhost/detail/My%20Product%20Name-123456789/ Should: http://localhost/detail/My-Product-Name-123456789/ 

I want to get rid of% 20 (which are also directly generated inside ui-sref = "") and replace them with minus (-).

Any ideas how to do this?

Regards, Marcus

+7
angularjs angular-ui-router
source share
2 answers

Register a custom type that outputs and discards data. Docs here: http://angular-ui.imtqy.com/ui-router/site/#/api/ui.router.util . $ UrlMatcherFactory

Define a custom type. Implement encoding, decode, there is a template:

  var productType = { encode: function(str) { return str && str.replace(/ /g, "-"); }, decode: function(str) { return str && str.replace(/-/g, " "); }, is: angular.isString, pattern: /[^/]+/ }; 

Now register your custom type as β€œproduct” with $urlMatcherFactoryProvider :

 app.config(function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) { $urlMatcherFactoryProvider.type('product', productType); } 

Now define your url parameter as a product, and the custom type will do the mapping for you:

  $stateProvider.state('baseproductdetail', { url: '/detail/{productName:product}-:productId/', controller: function($scope, $stateParams) { $scope.product = $stateParams.productName; $scope.productId = $stateParams.productId; }, template: "<h3>name: {{product}}</h3><h3>name: {{productId}}</h3>" }); 

Work panel: http://plnkr.co/edit/wsiu7cx5rfZLawzyjHtf?p=preview

+14
source share

A very simple approach:

In the controller where ui-sref is used (or even better in a separate service):

 $scope.beautyEncode = function(string){ string = string.replace(/ /g, '-'); return string; }; 

In the template:

 <a href="" ui-sref="base.product.detail({productName: beautyEncode(product.name), productId: product.id})"> 

The routing itself was not changed; angular did the correct routing.

+3
source share

All Articles