简体   繁体   中英

Angularjs History back button not working

I have been looking at loads of examples for the Angularjs Back Button event, but none of the examples have been working out for me. Whenever the browser back button is pressed, my code does not get the event. I have been scratching my head for days now.

All I want to do is getting an alert asking if the user is sure that they want to go back and loose all their data.

Below is the code that I have been trying. It is a copy from other examples, but with complete code.

I have tried to add the $on in the controller using the $scope instead of $rootscope, I have tried watch on routechangestart, nothing seem to catch the back button.

Does someone have a complete small example or tell me what I am doing wrong?

var BackButtonTest = angular.module('BackButtonTest', ['ngRoute']);

BackButtonTest.controller('backbuttonCtrl', function($scope, $location, $route) {
});

BackButtonTest.run(function($rootScope, $route, $location){
    //Bind the $locationChangeSuccess event on the //rootScope, so that we don't need to 
    //bind in induvidual controllers.

    $rootScope.$on('$locationChangeSuccess', function() {
        $rootScope.actualLocation = $location.path();
    });

    $rootScope.$watch(function () {
        return $location.path()
    }, function (newLocation) {
        if($rootScope.actualLocation === newLocation) {
        // run a function or perform a reload
        }
    });
});

The HTML code I have used is as follows:

<!doctype html>
<html lang="en" ng-app="BackButtonTest">
<head>
    <meta charset="utf-8">
    <title>BackButtonTest App</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.min.js"></script>
<script src="app.js"></script>
<body ng-controller="backbuttonCtrl as bbc">
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-8 col-md-push-2">
       Some random text
      </div>
    </div>
  </div>
</body>
</html>

I'd recommend using $locationChangeStart because that is where you can "prevent" the change from happening.

Logic is basically:

  1. Intercept the location change request.
  2. Determine if you need to show your modal
  3. If so preventDefault on the location change ( this will stop the change from happening)
  4. Save where the user wanted to go
  5. Show your modal
  6. If they click 'cancel' forget #4
  7. If they click ok, allow #4 to happen.

This link walks through the details of how to do it: http://weblogs.asp.net/dwahlin/cancelling-route-navigation-in-angularjs

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