本文介绍了angular ui.router ui-sref 替换 url 字符 - 美化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找替换 ui-sref 中字符的可能性,尊重目标的 URL.

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/'

URL 现在看起来像:

The URLs now look like:

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

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

我想去掉 %20(也是直接在 ui-sref="" 中生成的)并用减号 (-) 替换它们.

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?

问候,马库斯

推荐答案

注册用于编组和解组数据的自定义类型.文档在这里:http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.$urlMatcherFactory

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: /[^/]+/
  };

现在使用 $urlMatcherFactoryProvider 将自定义类型注册为product":

Now register the custom type as 'product' with $urlMatcherFactoryProvider:

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

现在将您的 url 参数定义为产品,自定义类型将为您进行映射:

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

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

这篇关于angular ui.router ui-sref 替换 url 字符 - 美化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 02:13