我在Angular JS中有一个'route',如下所示
$routeProvider.when('/foos/:fooId', { controller: FooController, templateUrl: 'foo.html'});
,它工作得很好,除非:fooId组件包含'/'或'%2F'(编码形式)
如何让这个工作,我的'fooId'可以包含/s ?
你不能轻易做到这一点,因为如果你使用一个链接与%2F
在它,浏览器会为你解码它,它将最终是/
。AngularJS目前不允许你在$route
参数中使用/
。
你可以对它进行双重编码,像这样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: '/'});
});
链接为:<a href="#/dir/a%252Fb%252Fc">click here</a>
.
另一个选项,如果你在参数中有一组/
字符,可以在这里找到:我如何让angular.js路由长路径
根据兰登的回答,我创建了一个过滤器,对所有内容进行两次编码,另一个用于解码:
.filter('escape', function() {
return function(input) {
return encodeURIComponent(encodeURIComponent(input));
};
})
.filter('unescape', function() {
return function(input) {
return decodeURIComponent(input);
};
});
我在我的产品链接中使用如下:
<a href="#/p/{{product.id}}/{{product.name | escape}}">
在产品页面上,我解码产品名称:
<h1>{{product.name | unescape}}</h1>
您不需要在这里编码任何内容。只需在路径参数中添加*,如下所述,并启用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
});
includelocationProvider.hashPrefix美元(");