简体   繁体   中英

How to show the back button only if it leads to the same single-page-application in AngularJS?

I know how to implement back button in AngularJS: How to implement history.back() in angular.js

And I want to display it only when BACK would lead me to the same application:

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

I would like BACK to be hidden if it would lead to some other page.

My current implementation looks like this:

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;
  }
});

This does not work.

When I paste http://127.0.0.1:9000/ into the browser bar the document.referrer is "" (empty string). However if I do this the following way: <a href="http://127.0.0.1:9000/#/search">now referrer will be correct</a>


Please advise.

document.referrer returns the entire url of the previous page, so if you want your function to work you can't check that it matches exactly.

Maybe try something less specific like checking document.referrer for the same hostname:

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

I've had to solve the same problem in an AngularJS app and I used the $window.history.length to make the determination. When the app initially loads, I save the initial history length in a variable. When the Back button is clicked I compare the current history length with the initial. If my current history is larger, I know that I can go back at least one page to my original starting point. The current index will never be smaller than the initial because its impossible to navigate "back" to a lower index and stay in the app.

This would look something like the following:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM