Showing alert in angularjs when user leaves a page

后端 未结 6 637
借酒劲吻你
借酒劲吻你 2020-11-28 22:04

I\'m an angularjs new bee. I\'m trying to write a validation which alerts the user when he tries to close the browser window.

I have 2 links on my page v1 and v2.Whe

6条回答
  •  感情败类
    2020-11-28 22:20

    Lets seperate your question, you are asking about two different things:

    1.

    I'm trying to write a validation which alerts the user when he tries to close the browser window.

    2.

    I want to pop up a message when the user clicks on v1 that "he's about to leave from v1, if he wishes to continue" and same on clicking on v2.

    For the first question, do it this way:

    window.onbeforeunload = function (event) {
      var message = 'Sure you want to leave?';
      if (typeof event == 'undefined') {
        event = window.event;
      }
      if (event) {
        event.returnValue = message;
      }
      return message;
    }
    

    And for the second question, do it this way:

    You should handle the $locationChangeStart event in order to hook up to view transition event, so use this code to handle the transition validation in your controller/s:

    function MyCtrl1($scope) {
        $scope.$on('$locationChangeStart', function(event) {
            var answer = confirm("Are you sure you want to leave this page?")
            if (!answer) {
                event.preventDefault();
            }
        });
    }
    

提交回复
热议问题