Display confirmation pop-up when clicking outside of the modal window in Bootstrap

I am currently utilizing AngularJS (1.5.9) and ui-bootstrap in my application. I am looking to display a confirmation popup if the user clicks outside of an already open modal.

I have attempted using both controlled exit with $uibModalInstance.close() and non-controlled exit with $uibModalInstance.dismiss(), but the modal closes before displaying the confirm popup.

I also tried using the backdrop: 'static' attribute, but was unable to capture a click event outside of the modal window.

Here is the HTML code:

<div ng-app="myApp">
    <script type="text/ng-template" id="myModal.html">
        <div class="modal-header">
            <h3 class="modal-title">Modal title</h3>
        </div>
        <div class="modal-body">
            Modal content
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </script>

    <div ng-controller="MyCtrl">
        <input type="button" value="Show modal" ng-click="showModal()"/>
    </div>
</div>

And here is the JS code:

angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {
    $scope.showModal = function(){
        $modal.open({
              templateUrl: 'myModal.html',
              controller: 'ModalDialogController', 
         })
        .result.then(
            function () {
                alert("OK");
            }, 
            function () {
                alert("Cancel");
            }
        );
    }
})

.controller("ModalDialogController", function ($scope, $modalInstance) {
  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('Cancel');
  };
});

You can also check out this related fiddle --> Fiddle

After opening the modal and clicking outside, there's an alert with 'Cancel'. However, I want to show another modal to confirm the action of closing the modal. If the user clicks 'Cancel', the previous modal should remain open. If they click 'OK', then both modals should close.

Any suggestions or ideas on how to achieve this?

Answer №1

Here is a demonstration for you to try:

Instead of using the traditional javascript confirmation dialog, you can use a modal popup for user confirmation.

Check out the code snippet below for implementing this feature:


angular.module('app', ['ui.bootstrap'])

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

    $scope.$on('modal.closing', function (event, reason, closed) {
        if (!closed) {

            if (!confirm('Are you sure you wanna close the modal? the database?')) {
                event.preventDefault();
            }
        }
    });

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

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
})


.controller('appCtrl', function ($scope, $uibModal) {
    
    $scope.open = function () {
        var modalInstance = $uibModal.open({
            templateUrl: 'myModal.html',
            controller: 'modalCtrl'
        }).result.then(
                function () {
                    alert("OK");
                },
                function () {
                    alert("Cancel");
                }
            );

    }
});


<!DOCTYPE html>
<html>

  <head>
    
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.3.2/ui-bootstrap-tpls.min.js"></script>
    
    <link data-require="bootstrap-css@*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
  </head>

  <body ng-app="app" ng-controller="appCtrl">
    <button ng-click="open()">Click me!</button>
     <script type="text/ng-template" id="myModal.html">
        <div class="modal-header">
            <h3 class="modal-title">Modal title</h3>
        </div>
        <div class="modal-body">
            Modal content
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </script>
  </body>

</html>

Answer №2

To ensure the functionality of your code, make sure to include backdrop: 'static' after controller: 'ModalDialogController'. This adjustment should guarantee its effectiveness.

angular.module("myApp", ['ui.bootstrap'])
.controller("MyCtrl", function($scope, $modal) {
    $scope.showModal = function(){
        $modal.open({
              templateUrl: 'myModal.html',
              controller: 'ModalDialogController', 
              backdrop: 'static'

         })
        .result.then(
            function () {
                alert("OK");
            }, 
            function () {
                alert("Cancel");
            }
        );
    }
})

.controller("ModalDialogController", function ($scope, $modalInstance) {
  $scope.ok = function () {
    $modalInstance.close();
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});

Answer №3


    const MyApp = angular.module("myApp", ['ui.bootstrap']);

   MyApp.controller("MyCtrl", function($scope, $modal) {
    $scope.displayModal = function(){
        $modal.open({
              templateUrl: 'myModal.html',
              controller: 'ModalDialogController', 
         })
        .result.then(
            function () {
                alert("Successful");
            }, 
            function () {
                var canProceed = confirm("Are you sure?");
                if (canProceed)
                    alert("Confirmed");
                else
                    alert("Cancelled");
            }
        );
    }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to generate flexible arrays using an established array?

Currently, I am working on creating a new array from an existing one. The structure of my current array is outlined below. How can I ensure that adding a new object results in a new array starting from that point? myArray: [{ anima ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Using Angular $resources in the query() function often results in the error message "Undefined is not a function

When I try to call the query() function using ngResource, I keep getting an error message saying "Undefined is not a function." [demo.js] var app = angular.module('StarterApp', ['ngResource']); app.factory("resourceFactory", function ...

Is there a method to ascertain the relative position of a point on a polygon?

Apologies in advance as I might have a hard time wording this question properly, so I'll start by explaining my objective. I'm currently working with JavaScript and Raphael. My goal is to save the position of a point in relation to the four cor ...

Struggling to properly implement an "Errors" Object in the state function of a React Login Form Component

The issue arose while I was following a React tutorial. My objective is to develop a basic social media web application using Firebase, React, MaterialUI, and more. I am currently at around the 5:40:00 mark and have successfully resolved all previous pro ...

javascript selecting window location strings

Hey there, http://localhost/estamo/asset.php?aname=VklQIFBsYXph&di=Ng== I have this URL and I want to retrieve it using Javascript: var locat = window.location.href; $.get("enviaramigo.php?email="+$("#email").val()+"&url="+locat, function(h ...

Executing a cloud function in Firebase from an Angular-Ionic application by making an HTTP request

I am a newcomer to GCP and app development, so please bear with me if this question seems mundane. Currently, I have an angular-ionic app that is connected to Firebase allowing me to interact with the Firestore database. Now, my challenge is to invoke a ht ...

Flashing bug in the outFunction of jquery hover()

My friends and I are working on a website for a class project, but we're running into a strange issue with the outFunction part of our hover function. Whenever the mouse hovers over an element, a grey square fades in using .fadeIn(), but then immediat ...

Sending a XML file from a Vue application to an ASP.NET Core backend using axios

I'm encountering difficulties when trying to upload an xml file using axios to my asp .net server. Below is the code snippet I am using on the vue side to retrieve and upload the xml file: uploadXmlFile(file: any) { const rawFile = new XMLHttpRequ ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...

Exploring the implementation of window.addEventListener within an Angular project

I am currently working on testing a method in Angular using Jasmine. However, I am running into an issue with triggering the mouse event (specifically when the browser back button is clicked). Below is the code snippet I'm working with: navigate() { ...

Encountering issues with JavaScript/ajax if statement functionality

Driving me insane! Dealing with 2 modal forms - one for login and another for registration. Javascript handles client-side validation, followed by an ajax call to either a registration or login php file. The PHP files return 'OK' if successful or ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

Generating new elements on the fly using jQuery and passing a string parameter through the onclick event

While dynamically creating HTML, I encountered a syntax error. If I modify href="javascript:startChat(' + user_id + ','video')" to href="javascript:startChat(' + user_id + ','"video"')", I receive an error stating &a ...

Integrating Mailchimp with MongoDB and Node.js

As of now, I am managing a database of users in MongoDB and my goal is to provide them with regular updates on new content available on a real-estate marketplace website on a daily basis. My plan is to send out email notifications to each user every day w ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

Issues encountered with integrating external jQuery/JavaScript functions with Wordpress child theme template

After creating a custom template in my WordPress child theme, I added a link to the Bootstrap v3.0.3 .js file stored on my site. While the popup modal is functioning properly, the jQuery tabs seem to be having some issues. Although they are being display ...

Wizard for the advanced tab panel

I am facing a challenge with my advanced TabPanel Wizard. It consists of 4 tabs, each serving as its own form to allow for validation within the tab itself. The issue I am encountering is related to the validation behavior of non-rendered tabs. One proble ...

Unexpected interactions between Socket.io and React using hooks

Currently, I am delving into the world of Socket.io with React utilizing Hooks. My goal is to create a timer that starts upon pressing the start button, and then every second, send the current time in the state to the server using socket.io. The server co ...