Mark Mark - 1 year ago 127
AngularJS Question

Prevent AngularJS modal from closing based on logic inside the modal controller

Is there a way to prevent the an AngularJS modal from closing/dismissing in the controller logic of the modal?

What I want is to show a warning when the users closes the modal and the form inside the modal contains unsaved data.

I've tried searching for a before close event or something else I could use in the official documentation, but no luck so far.

Answer Source

You can watch the 'modal.closing' event, broadcasted to the modal's scope, like this:

.controller('modalCtrl', function($scope, $modalInstance) {

  $scope.$on('modal.closing', function(event, reason, closed) {
      var r = prompt("Are you sure you wanna close the modal? (Enter 'YES' to close)");

      if (r !== 'YES') {

The first parameter is the event, which you can preventDefault() to prevent it from closing.

The second parameter is the reason (whatever is passed to the $close() method)

The third parameter is a boolean indicating whether the modal was closed or dismissed.

Here a working plunker

I don't know when this was added, but currently it is mentioned in the official documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download