【问题标题】:disable'$scope.$on('$locationChangeStart' )' if user click cancel?如果用户单击取消,则禁用'$scope.$on('$locationChangeStart')'?
【发布时间】:2015-08-31 02:34:33
【问题描述】:

当用户单击取消时我遇到了问题,它确实会重定向,我会触发$scope.$on('$locationChangeStart'),因为我会有'您有未保存的更改。如果您继续,您的更改将会丢失。出现两次。只想问如果用户单击取消,我该如何禁用'$scope.$on('$locationChangeStart')'

代码

$scope.cancel = function() {
    var validator = npFormValidator($scope);
    if ($scope.npForm.$dirty) {
        var answer = confirm('You have unsaved changes.  If you continue your changes will be lost.');
        if (answer) {
            $location.path('/home');
        } else {
            validator.addWatches();
            event.preventDefault();

        }
    }
};


$scope.$on('$locationChangeStart', function (event) {
    var validator = npFormValidator($scope);
    if (validator.valid() && $scope.model.clickedSave) {
        window.onbeforeunload = undefined;
    } else {
        if ($scope.npForm.$dirty) {
        var answer = confirm('You have unsaved changes.  If you continue your changes will be lost.');
            if (!answer) {
                validator.addWatches();
                event.preventDefault();
            }
        }
    }
})

;

【问题讨论】:

    标签: angularjs ngroute cancellation


    【解决方案1】:

    您可以设置一个标志并在您的事件接收器中检查它:

    var canceled = false;
    $scope.cancel = function() {
        var validator = npFormValidator($scope);
        if ($scope.npForm.$dirty) {
            var answer = confirm('You have unsaved changes.  If you continue your changes will be lost.');
            if (answer) {
                canceled = true;
                $location.path('/home');
            } else {
                canceled = false;
                validator.addWatches();
                event.preventDefault();
    
            }
        }
    };
    
    $scope.$on('$locationChangeStart', function (event) {
        if (canceled) return;
        var validator = npFormValidator($scope);
        if (validator.valid() && $scope.model.clickedSave) {
            window.onbeforeunload = undefined;
        } else {
            if ($scope.npForm.$dirty) {
            var answer = confirm('You have unsaved changes.  If you continue your changes will be lost.');
                if (!answer) {
                    validator.addWatches();
                    event.preventDefault();
                }
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-22
      • 2017-12-04
      • 1970-01-01
      • 2012-02-23
      • 2020-04-09
      相关资源
      最近更新 更多