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

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

    You'd be better off using $stateChangeStart event with angular ui router. There will be problems with $routeChangeStart as $routeChangeStart event will be triggered when the url changes.

    For example:

    You have 4 states, each with 2 sub-state, and each sub/state or state is not associated with a url. In such cases listening to $routeChangeStart might not work.

    In the controller/view where you want to prompt the user to confirm the redirection do this.

    This will be called when the state changes in your current scope (which is the view/controller that you are in)

    $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        //Open the modal
        $('my-modal').show();
    });
    

提交回复
热议问题