2014-10-30 28 views
1

我想創建一個只能從應用程序代碼和鏈接訪問的angularJs路線。主要想法是阻止用戶在瀏覽器的地址欄中直接輸入路由URL後訪問該頁面。 對於路由配置,我使用「ngRoute」模塊的$ routeProvider。只允許從應用程序代碼/鏈接訪問AngularJS路線

我找不到這個問題的答案。我需要的東西可能嗎?

在此先感謝。

回答

1

你可以聽$locationChangeStart事件。在你的路線,你可以設置一個參數(我把它叫做「限制」,但你可以把它任何你想要的)是這樣的:

app.config(function($routeProvider) { 
    $routeProvider 
    .when('/', { 
     controller: 'MainCtrl', 
     template: 'Allowed from anywhere.<br>Go to main <a href=\"#/main\">page</a>', 
     restricted: false 
    }) 
    .when('/main', { 
     controller: 'MainCtrl', 
     template: 'Allowed from anywhere.<br>Go to restricted <a href=\"#/restr\">page</a>', 
     restricted: false 
    }).when('/restr', { 
     controller: 'RestrictedPageCtrl', 
     template: 'Allowed only from main', 
     restricted: '/main' 
    }); 
}); 

如果是假的,這意味着沒有限制,如果它被設置爲路徑,那麼只能從該路徑訪問路線。你還可以用這個檢查:

app.run(function($rootScope, $location, $route) { 
    $rootScope.$on('$locationChangeStart', function(event, next, current) { 
    var nextRoute = $route.routes[$location.path()]; 
    var currentPath = current.split('#')[1]; 
    if (nextRoute.restricted && nextRoute.restricted !== currentPath) { 
     $location.path('/'); 
     alert('You are trying to reach a restricted page!!!!'); 
    } 
    }); 
}); 

你可以改變的行爲和用戶重定向到另一個鏈接或防止位置變化與event.preventDefault();

請注意,如果您在鏈接(html5Mode)中未使用#標籤(#),則應更改獲取當前鏈接的方式。

這是plunker

+0

非常感謝。 – 2014-10-31 07:52:25

+0

對不起,我不能upvote,因爲我剛剛在這裏註冊,我還沒有足夠的投票聲望呢。所以我只能接受答案。 – 2014-10-31 11:00:26

相關問題