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

What are the steps to create a new website with a MEAN stack application on a Windows 10 home computer?

A few days ago, I successfully installed the MEAN stack application on my Windows 10 system. However, I am unsure of how to proceed with creating a new website using this MEAN stack application. Can anyone provide guidance on how to go about building a w ...

What is the best approach to establish multiple global prefixes in a NestJS project?

I am looking to define multiple Global Prefixes for my application such as: admin/products admin/users admin/... api/products api/search api/... shop/products shop/cart shop/... In the main.ts file, I can set a single global prefix using th ...

Using optional chaining on the left side in JavaScript is a convenient feature

Can the optional chaining operator be used on the left side of an assignment (=) in JavaScript? const building = {} building?.floor?.apartment?.number = 3; // Is this functionality supported? ...

Achieving a single anchor link to smoothly scroll to two distinct sections within a single page using React

There is a sidebar section alongside a content section. The sidebar contains anchor links that, when clicked, make the corresponding content scroll to the top on the right-hand side. However, I also want the sidebar link that was clicked to scroll to the ...

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

The Vue component does not render the JS Promise and instead displays it as

After setting up a promise that will be returned once a correct event is called with the correct action, I have the following code: import {EventBus} from "./EventBus"; export function completed() { EventBus.$on('queue-action', e => { ...

Retrieve storage information when an internet connection is unavailable on React Native

One of my recent projects involves creating an application that retrieves data from a URL in the form of an array of objects and then displays this data using FlatList. Upon launching the application, the data is displayed correctly since it's retriev ...

Encountering an issue with using third-party APIs due to receiving an error message stating that the requested resource does not have the 'Access-Control-Allow-Origin' header

My current challenge involves attempting to access a third-party API using AngularJS. Interestingly, I only encounter this issue in Chrome, as it works perfectly fine in IE. The error message that pops up reads as follows: XMLHttpRequest cannot load https ...

Currency unique to a specific culture

Recently, I encountered an issue while working on a website that involved using JavaScript code to format currency values. Here is the snippet of code that was causing the problem: UsdAmount.toLocaleString(siteCulture, {style: 'currency', ...

Having trouble connecting to JSTL in my JavaScript file

Currently, I am facing an issue with my JSTL code that is housed within a JavaScript file being included in my JSP page. The problem arises when I place the JSTL code inside a script within the JSP page - it works perfectly fine. However, if I move the s ...

Tips for displaying a pre-filter loading message using AngularJS

Is there a way to display a "Loading Message" prior to the filtered data being returned when using AngularJS for filtering? The filter process is quick, so displaying the message before returning the filtered data is not feasible. Here is an example of the ...

Utilizing Vue.js for Keyboard Binding

I'm brand new to coding and Vue, and I've hit a roadblock in my project. I'm creating a JavaScript calculator that needs to be usable both with a mouse and keyboard. While I've managed to make it work with the mouse, I just can't ...

Is it possible to transmit an array using $.ajax and specify the dataType as json?

I am currently attempting to send a JavaScript array to my .php file handler and store it in my database. Although the request is successful, it seems like my array isn't being posted/saved correctly. When I check the POST request source, it shows up ...

Issue encountered when attempting to delete object using DELETE request

I've recently started working with node.js and I'm attempting to remove an object from a JSON file when making a DELETE request. Despite my efforts, the object isn't being deleted as expected. Here is the code I have written: const express = ...

A step-by-step guide to implementing the PUT function in AngularJS using Mongoose

My attempt to send a GET request to the Mongo works fine, but I'm having trouble getting the PUT request to work. My suspicion is that there might be an issue with the path from the controller to the router. I've already tried using both update() ...

Managing changes to object properties in Angular

I am encountering a situation where I have an object containing both an 'id' and 'name' property, structured like this: function format(id){ return '(' + id + ')'; } function MyObject(id){ this.id = id; this. ...

Is there a way to integrate jQuery and Javascript into a Firefox add-on?

Having trouble creating a new element on the page? After checking both the page and domain during onload, it seems that everything is in order. But how can you successfully create a new element in the correct window page? window.addEventListener("load", f ...

retrieve information from a div using an AJAX request

I don't have much experience with ajax and javascript, but I need some assistance, so I will do my best to explain clearly! Below is the JavaScript associated with a button: $('#button-confirm').on('click', function() { $.ajax({ ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Using Jquery to swap out div elements and reinitialize code after selecting a menu <a href>link<</a>

I have a jQuery script that swaps out a div when a href="#1" is clicked. The same link, a href="#1", is then replaced by a href="#2" and vice versa. Here is the jQuery code: $('.child2, a[href="#1"]').hide() $('#replacepagelinks a').c ...