angular ui.router ui-sref replace url characters - beautify

梦想的初衷 提交于 2019-11-30 05:14:07

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!