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

前端 未结 4 1054
南旧
南旧 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:39

    Here is my solution

    app.run(function($rootScope, $location) {
        $rootScope.$on('$locationChangeSuccess', function() {
            if($rootScope.previousLocation == $location.path()) {
                console.log("Back Button Pressed");
            }
            $rootScope.previousLocation = $rootScope.actualLocation;
            $rootScope.actualLocation = $location.path();
        });
    });
    

提交回复
热议问题