我需要在AngularJS路由中定义一条路径:
参数值的一些示例是:
/ABC
/ABC/123
/ABC/123/XYZ
我试过了
'/Documents/:folderUrl*'
负责处理参数值中的/
字符,但如果参数为空,则转到.otherwise()。
'/Documents/:folderUrl?'
使其成为可选项,但由于/ABC/123
字符,我无法将/
作为值。
我不想有两个.when(),因为我怀疑它会加载控制器两次,这是我解释的一个问题here。
答案 0 :(得分:1)
在网址中传递带编码的斜杠非常困难,因为浏览器会将其更改为斜杠。我想出的唯一解决方案是对斜杠进行双重编码。我使用this encoder进行编码,但如果需要,可以使用encodeURIComponent
在角度应用中完成。这意味着网址是#/Documents/ABC%252F123
。
要设置参数,首先必须将其添加到app.js
中的路由配置中。我添加了名为url
的参数,并使用?
符号将其设为可选:
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/Documents/:url?', {
templateUrl: 'view.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/Documents/'
});
});
然后在您的控制器中,您可以使用$routeParams
来获取网址。但由于斜杠是双重编码的,因此您需要使用decodeURIComponent
来解码网址:
app.controller('MainCtrl', function($scope, $routeParams) {
$scope.url = decodeURIComponent($routeParams.url);
})
点击演示中的a
链接,查看正在传递的网址。