Angular JS'route'与%2F(编码'/')的组件不匹配

Con*_*oob 18 javascript html5 angularjs

我在Angular JS中有一个'route',如下所示

$routeProvider.when('/foos/:fooId', { controller: FooController, templateUrl: 'foo.html'});
Run Code Online (Sandbox Code Playgroud)

并且效果很好,除非:fooId组件包含'/'或'%2F'(编码形式)

我怎么能做这个工作,我的'fooId'可以包含/ s?

Lan*_*don 12

你不能轻易做到这一点,因为如果你使用其中的链接%2F,浏览器将只为你解码它,它最终会成为/.AngularJS目前不允许您/$routeparams中使用.

你可以对它进行双重编码,就像在这个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: '/'});

});
Run Code Online (Sandbox Code Playgroud)

链接将是:<a href="#/dir/a%252Fb%252Fc">click here</a>.

另一个选项,如果/参数中有一定数量的字符,可以在这里找到:如何使angular.js路由长路径

  • 我不得不手动双重编码和重新编码:function encodeSlash(uri){return uri.replace(/\/ // g,'%252F').replace(/%2F/gi,'%252F'); } function decodeSlash(uri){return uri.replace(/%2F/gi,"/"); 这些都是在写入$ location或者读取时使用的(例如来自$ routeParams),但是效果很好,谢谢! (2认同)

For*_*ega 5

基于兰登的答案,我创建了一个过滤器,它对所有内容进行了两次编码,另一个进行了解码:

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

.filter('unescape', function() {
        return function(input) {
            return decodeURIComponent(input);
        };
    });
Run Code Online (Sandbox Code Playgroud)

我在我的产品链接中使用它如下:

<a href="#/p/{{product.id}}/{{product.name | escape}}">
Run Code Online (Sandbox Code Playgroud)

在产品页面上,我解码产品名称:

<h1>{{product.name | unescape}}</h1>
Run Code Online (Sandbox Code Playgroud)


小智 5

您无需在此处进行任何编码。只需如下所述在路径Param中添加*并启用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
 });
Run Code Online (Sandbox Code Playgroud)