Angular JS 'route' doesn't match component with / (encoded '/')

前端 未结 4 823
难免孤独
难免孤独 2021-01-07 20:05

I have a \'route\' in Angular JS as follows

$routeProvider.when(\'/foos/:fooId\', { controller: FooController, templateUrl: \'foo.html\'});

相关标签:
4条回答
  • 2021-01-07 20:32

    include $locationProvider.hashPrefix(''); in your config.

    0 讨论(0)
  • 2021-01-07 20:33

    You need not to encode anything here. Just add * in your path Param as mentioned below and enable html5Mode

     app.config(function ($routeProvider, $locationProvider) {
     $routeProvider
    .when('/home', {templateUrl: 'home.html', controller: 'HomeCtrl'})
    .when('/base/:path*', {templateUrl: 'path.html', controller: 'pathCtrl'})
    .otherwise({redirectTo: '/home'});
    });
    
     $locationProvider.html5Mode({
      enabled: true,
      requireBase: false
     });
    
    0 讨论(0)
  • 2021-01-07 20:41

    You can't easily do this because if you use a link with %2F in it, the browser will just decode it for you and it'll end up being /. AngularJS currently doesn't allow you to use / in $route params.

    You can double encode it, like in this plnkr: http://plnkr.co/edit/e04UMNQWkLRtoVOfD9b9?p=preview

    var app = angular.module('app', []);
    
    app.controller('HomeCtrl', function ($scope, $route) {
    });
    app.controller('DirCtrl', function ($scope, $route) {
      var p = $route.current.params;
    
      $scope.path = decodeURIComponent(p.p1);
    });
    
    app.config(function ($routeProvider) {
        $routeProvider
                .when('/', {templateUrl: 'home.html', controller: 'HomeCtrl'})
            .when('/dir/:p1', {templateUrl: 'dir.html', controller: 'DirCtrl'})
                .otherwise({redirectTo: '/'});
    
    });
    

    And the link would be: <a href="#/dir/a%252Fb%252Fc">click here</a>.

    Another option, if you have a set number of / characters in your parameters can be found here: How can I make the angular.js route the long path

    0 讨论(0)
  • 2021-01-07 20:49

    Based on the answer of Langdon, I created a filter which encodes everything twice, and another one which decodes:

    .filter('escape', function() {
            return function(input) {
                return encodeURIComponent(encodeURIComponent(input));
            }; 
    })
    
    .filter('unescape', function() {
            return function(input) {
                return decodeURIComponent(input);
            };
        });
    

    I use this in my product links as follows:

    <a href="#/p/{{product.id}}/{{product.name | escape}}">
    

    On the product page, I decode the product name:

    <h1>{{product.name | unescape}}</h1>
    
    0 讨论(0)
提交回复
热议问题