尝试离开页面时,为什么我的确认消息不起作用?

时间:2018-12-18 21:16:16

标签: angularjs

为什么我尝试离开页面时确认消息不起作用?

<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>
    <a href="https://w3schools.com">W3Schools</a>

    <div ng-app="myApp" ng-controller="formCtrl">
        <form novalidate>
            First Name:<br>
            <input type="text" ng-model="user.firstName"><br>
            Last Name:<br>
            <input type="text" ng-model="user.lastName">
            <br><br>
            <button ng-click="reset()">RESET</button>
        </form>
        <p>form = {{user}}</p>
        <p>master = {{master}}</p>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('formCtrl', function ($scope) {
            $scope.$broadcast('$locationChangeStart');


            $scope.master = { firstName: "John", lastName: "Doe" };
            $scope.reset = function () {
                $scope.user = angular.copy($scope.master);
            };
            $scope.reset();

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

</html>

1 个答案:

答案 0 :(得分:0)

您应该改用onbeforeunload

这将使您在页面即将被卸载时(或称为“离开页面”)有正确的确认消息。