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

后端 未结 2 591
你的背包
你的背包 2020-12-29 11:57

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/:p         


        
2条回答
  •  长情又很酷
    2020-12-29 12:28

    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: "

    name: {{product}}

    name: {{productId}}

    " });

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

提交回复
热议问题