disable'$scope.$on('$locationChangeStart' )' if user click cancel?

714 views Asked by At

I have problem when the user click cancel and it is true it will redirtect i it will trigger $scope.$on('$locationChangeStart') becouse of that I will have 'You have unsaved changes. If you continue your changes will be lost.' appear twice. just want to ask how can I disable'$scope.$on('$locationChangeStart' )' if user click cancel

code

$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();
            }
        }
    }
})

;

1

There are 1 answers

0
alisabzevari On BEST ANSWER

You can set a flag and check it in your event receiver:

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();
            }
        }
    }
});