Angular ui-sref encode parameter

2019-01-18 14:10发布

问题:

My router looks like that:

.state('project', {
        'url': '/project/*path',
        'controller': 'ProjectController',
        'templateUrl': '/pages/project.html',
    });

but when I use

ui-sref="project({path: mypath})"

with mypath=part1/part2 I expect the it to turn into /project/part1/part2 but instead i get /project/part1%252Fpart2.

How can I make it pass parameter without encoding it ?

回答1:

As it was described here, you need to declare custom variable type for URL param in order to have slashes not encoded. Quoting comment from github:

If you really don't want the slash encoded for you, register a custom type with your regexp and declare item_id to be your custom type, i.e., url: /{item_id:MyType}

function valToString(val) { return val != null ? val.toString() : val; }
function valFromString(val) { return val != null ? val.toString() : val; }
function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); }
$urlMatcherFactory.type("MyType", {
  encode: valToString,
  decode: valFromString,
  is: regexpMatches,
  pattern: /[^/]+\/[^/]+/
});


回答2:

To resolve this problem you can change a state by using $location.path(), which has slashes in stateparams. For example if our state is like this:

app.js

.state('project', {
    'url': '/project/*path',
    'controller': 'ProjectController',
    'templateUrl': '/pages/project.html',
});

In this case path param may contains multiple slashes .If path=part1/part2 then you get route like this /project/part1%252Fpart2 by using ui-sref or $state.go(). So to get correct routing (i.e. /project/part1/part2), use $location.path() to change a state.

HTML:

<a ng-click="goToMyState()">{{label}}</a>

Controller :

$scope.goToMyState = function () {
    var path = '/part1/part2'
    $location.path('/project' + path);
};


回答3:

in new ui-router 1.0 we can use raw:true param which will disable url-encoding of parameter as described here

    //link to state
<md-button ui-sref="content({slug:'hello-world/'})">Hello world</md-button>

$urlMatcherFactoryProvider.type('SlashFix', {
      raw:    true,
    });


    $stateProvider
      .state('content',{
       url: '/{slug:SlashFix}',
       ...

More detailed explanation can be found here:

https://www.coditty.com/code/angular-ui-router-replacing-slash-with-2f-quick-fix