2015-02-09 77 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