How to detect if a user clicks browser back button in Angularjs

前端 未结 4 1047
南旧
南旧 2020-12-02 21:11

I have a form-like page with some data. And want to show a popup/alert when a user clicks the browser back button, asking \"if they want to go back or stay on the same page\

4条回答
  •  遥遥无期
    2020-12-02 21:53

    Similar to syraz37's answer, but for the new $transition API:

    angular
        .module('app')
        .run(function($rootScope, $transitions) {
    
            // Track "previous state" to be used elsewhere to determine if the user
            // goes "back".
            $transitions.onStart({}, (transition) => {
                if ($rootScope._previousState === transition.$to().name) {
                    $rootScope._isPreviousState = true;
                } else {
                    $rootScope._isPreviousState = false;
                }
                $rootScope._previousState = transition.$from().name;
            });
    
        });
    

    Then in any controller, you can check if it's being loaded as the "previous state":

    if ($rootScope._isPreviousState) {
        // ...reload some aspect of the controller state...
    }
    

    This falls to the caveat pointed out by ninjaPixel above where you could go to state A, then state B, then state A again (all in a forward direction) and it would think the user has gone "back", but for our needs this works.

提交回复
热议问题