10

I'm searching for a possibility to replace characters in the ui-sref, respecting the URL of a target.

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

The URLs now look like:

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

Should:
http://localhost/detail/My-Product-Name-123456789/

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

Any ideas how to do that?

Regards, Markus

Markus
  • 1,069
  • 8
  • 26

2 Answers2

16

Register a custom type that marshalls and unmarshalls the data. Docs here: http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.$urlMatcherFactory

Let's define a custom type. Implement encode, decode, is and pattern:

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

Now register the 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>"
  });

Working plunk: http://plnkr.co/edit/wsiu7cx5rfZLawzyjHtf?p=preview

Chris T
  • 8,186
  • 2
  • 29
  • 39
  • Is it possible to use custom types so curly brackets( { ) not apper as '%7B' in the URL? Reference to this question I have made http://stackoverflow.com/questions/35204064/angular-ui-router-curly-brackets-etc-in-url – Devl11 Feb 11 '16 at 08:06
  • How to replace spaces with plus sign (+)? I've tried changing "-" with "+" but it's not working. Thanks. – Alberto I.N.J. Sep 02 '16 at 14:57
4

Very easy approach:

In the controller, where the 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 wasn't changed, angular did the routing still correctly.

Markus
  • 1,069
  • 8
  • 26