Angular ui-sref encode parameter

后端 未结 3 1238
Happy的楠姐
Happy的楠姐 2020-12-10 06:09

My router looks like that:

.state(\'project\', {
        \'url\': \'/project/*path\',
        \'controller\': \'ProjectController\',
        \'templateUrl\':         


        
相关标签:
3条回答
  • 2020-12-10 06:33

    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);
    };
    
    0 讨论(0)
  • 2020-12-10 06:33

    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

    0 讨论(0)
  • 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: /[^/]+\/[^/]+/
    });
    
    0 讨论(0)
提交回复
热议问题