Sjors Hijgenaar Sjors Hijgenaar - 3 months ago 56
AngularJS Question

Confirm angular modal closing on dirty form

I have an Angular-UI modal with a form in it. When the user triggers the dismiss event I want to implement a confirmation based on $dirty. I have searched through numerous sources to find notions on Promise and can succesfully get e.g. an alert during the closing event. However, I can't find anywhere how to actually stop the modal from closing.

EDIT:

With the current code the confirmation alert often (surprisingly not always) pops up after the modal has already been dismissed.

var editResourceModalController = function($scope, $uibModalInstance) {

$uibModalInstance.result.catch(function() {
if ($scope.editForm.$dirty) {
window.confirm("close modal?");
}
$uibModalInstance.dismiss('cancel');
});

}

var uibModalInstance;
$scope.openEditModal = function() {
uibModalInstance = $uibModal.open({
animation: true,
templateUrl: "edit.html",
controller: editResourceModalController
});
}

Answer

I fixed it using $scope.$on, extensive example here

var editResourceModalController = function($scope, $uibModalInstance) {

    $scope.close = function() {
        $uibModalInstance.close();
    }

    $scope.$on('modal.closing', function(event) {
        if ($scope.editForm.$dirty) {
            if (!confirm("U sure bwah?")) {
                event.preventDefault();
            }
        }

    });
}

var uibModalInstance;
$scope.openEditModal = function(editItem, hierarchy, selectedFolder) {
    uibModalInstance = $uibModal.open({
        animation: true,
        templateUrl: "edit.html",
        controller: editResourceModalController           
    });
}