[英]How to show the back button only if it leads to the same single-page-application in AngularJS?
我知道如何在AngularJS中实现后退按钮: 如何在angular.js中实现history.back()
而且我只想在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>
请指教。
document.referrer
返回上一页的整个url,因此如果您希望函数正常工作,则无法检查它是否完全匹配。
也许尝试一些不太具体的东西,比如检查document.referrer
是否有相同的主机名:
$rootScope.isBackAvailable = function() {
var result = _.contains(document.referrer, window.location.hostname);
console.log(result)
return result;
};
我必须在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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.