2014-05-24 27 views
0

我知道如何在AngularJS實現後退按鈕:How to implement history.back() in angular.js如何僅在AngularJS中顯示相同的單頁應用程序時顯示後退按鈕?

我想要顯示它,只有當BACK將導致我相同的應用程序:

<a ng-click="back()" ng-show="isBackAvailable()">BACK</a> 

我想BACK到如果它會導致其他頁面被隱藏。

我當前的實現看起來是這樣的:

app.run(function($rootScope, $window) { 
    var acceptableReferrers = ["http://127.0.0.1:9000/"]; 

    $rootScope.back = function() { 
    $window.history.back(); 
    } 

    $rootScope.isBackAvailable = function() { 
    var result = _.contains(acceptableReferrers, document.referrer); 
    console.log(result) 
    return result; 
    } 
}); 

這是行不通的。

當我粘貼http://127.0.0.1:9000/到瀏覽器欄document.referrer""(空字符串)。但是,如果我這樣做了以下方法: <a href="http://127.0.0.1:9000/#/search">now referrer will be correct</a>


請指教。

+0

你可以嘗試使用'$ location.absUrl()',然後檢查URL包含任何可接受的引薦 – callmekatootie

+0

@callmekatootie - ''' $ location.absUrl()'''嘗試使用它,但不適用於我:( –

+0

你的意思是它不會返回任何東西? – callmekatootie

回答

1

document.referrer返回上一頁的整個url,所以如果你想讓你的函數工作,你不能檢查它完全匹配。

也許嘗試不太具體如檢查document.referrer爲同一主機的東西:

$rootScope.isBackAvailable = function() { 
    var result = _.contains(document.referrer, window.location.hostname); 
    console.log(result) 
    return result; 
}; 
+0

只要用戶將地址粘貼到地址欄中,document.referrer就會是空的,根據問題,這是失敗的。不瘦這將有助於這一點。 – JeffB

+0

這是一個單頁面應用程序,'''document.referrer'''總是'''http://127.0.0.1:9000/「'''無論我的位置和應用程序中有多少點擊製作。 –

1

我不得不解決的AngularJS應用同樣的問題,我用$window.history.length進行判斷。當應用程序最初加載時,我將初始歷史長度保存在一個變量中。當單擊「後退」按鈕時,我將當前歷史長度與初始值進行比較。如果我目前的歷史記錄較大,我知道我可以至少回到一個頁面到我原來的起點。目前的指數永遠不會比最初的指數小,因爲它不可能導航回到較低的指數並留在應用程序中。

這看起來像下面這樣:

app.run(function($rootScope, $window) { 
    var historyLength = $window.history.length; 

    $rootScope.back = function() { 
    $window.history.back(); 
    } 

    $rootScope.isBackAvailable = function() { 
    return $window.history.length > historyLength; 
    } 
}); 
相關問題