2015-02-09 76 views
0

我需要定义在AngularJS路径路由到:如何使用?和*在角路由

  1. 有一个可选参数
  2. 有它接受一些实例相对路径的值

用于该参数值是:

/ABC 
/ABC/123 
/ABC/123/XYZ 

我已经试过

'/Documents/:folderUrl*' 

它会处理参数值中的/字符,但如果参数为空,则会转到.otherwise()。

'/Documents/:folderUrl?' 

使得可选的,但不能让我有/ABC/123如因/字符的值。

我不喜欢有两个.when(),因为我怀疑它加载控制器两次,这是我已经解释here的问题。

+0

我不明白“不允许我把它空的。”你想要什么是空的? – 2015-02-09 15:21:03

+0

去.otherwise() – 2015-02-09 15:28:58

回答

1

在浏览器将其更改为斜杠时,在URL中传递编码的斜线相当困难。我想出的唯一解决方案是对斜杠进行双重编码。我使用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得到的URL。但由于斜线双重编码,你需要使用decodeURIComponent到url解码:

app.controller('MainCtrl', function($scope, $routeParams) { 
    $scope.url = decodeURIComponent($routeParams.url); 
}) 

点击试玩a链接查看传递的网址。

Demo