Tips for personalizing the close dialog feature in ngDialog

I am working on implementing a unique custom close dialog feature for the close button of ngDialog.

Based on specific requirements, in certain scenarios (particularly those involving a form), I need to display an additional ngDialog confirmation popup that prompts the user to confirm whether they truly want to close the dialog. This secondary dialog presents two options: 'YES' and 'NO', each with its own functionality.

My initial attempt involved using the preCloseCallback() method, however this approach did not yield the desired outcome as it failed to wait for user confirmation. Essentially, the function is triggered upon clicking the close button, resulting in the immediate closure or persistence of the dialog based on the return value of the function. If no explicit return value is provided, the dialog assumes a true value and proceeds with closing.

If anyone has suggestions on how to address this issue, I would greatly appreciate your input.

Answer №1

Behold, the wonderful solutions are here! Although a bit hacky, they worked like magic for my particular situation.

Step 1

To prevent popup close while opening dialog, set the showClose option to false.

// Inside controller
PopUpFactory.openModal('SOME_NAME','SOME_URL.html', 'ngdialog-theme-default SOME_EXTRA_CSS', $scope, function(value){
    console.log("Done:", value);
},'SOME_CONTROLLER',false); // false sets **showClose** option as false

// Inside common Factory
function openModal(name, templateUrl, classes, scope, callback, ctrl, showClose){
    if(showClose === undefined){
        showClose = true;
    }
    ngDialog.openConfirm({
        name: name,
        controller: ctrl,
        template: templateUrl,
        className: classes,
        closeByDocument: false, 
        closeByEscape: false,   
        closeByNavigation : true,
        scope: scope,
        disableAnimation: true,
        showClose: showClose,
        preCloseCallback: function(value) {
            return true;
        }
    }).then(function (value) {
        callback(value);
    });
}

Step 2

Create a universal function to handle close button actions

// In Common Factory
/**
 * Customize close for any open modal form
 * @param isDirty - flag indicating if form is dirty
 * @param $scope - current form's scope object
 * @param $event - $event object from close button of open form
 */
var closeConfirmOpen = false;
function closeForm(isDirty,$scope,$event){
    // Prevent default behavior of ngDialog close event
    if($event){
        $event.preventDefault();
        $event.stopPropagation();   
    }
    
    if(isDirty){
        var msg = $filter('translate')('navigateAwayWithoutSavingConfirmMsg');
        closeConfirmOpen = true;
        confirmPopUp('Warning', msg, null, 'leavePage', 'red', 'stayOnPage', function(isOK){
        if(isOK == 1){ 
            $scope.closeThisDialog();
        }
        closeConfirmOpen = false;
    });
}else{
    $scope.closeThisDialog();
}
}

Step 3

Add a close function in the controller to invoke the factory function

/**
 * Close sample location modal
 */
$scope.closeForm = function($event){
 PopUpFactory.closeForm($scope.formName.$dirty,$scope,$event);
}

Step 4

Insert the following line after defining the header/title in the HTML of ngDialog

<div id="SOME_ID" class="ngdialog-close" ng-click="closeForm($event)"></div>

Hurrah... job well done...!!!

The beauty of these solutions lies in the reusable code for closing any form. Once you've set up the factory function, all you need to do is add a close button wherever needed in the HTML and include a simple close function in the controller.

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

Utilizing absolute positioning with a rotated div element

The situation I am facing involves a parent div and child div. The child div is positioned absolutely with respect to the parent div and has been rotated by an angle of 90 degrees. Due to the fact that the origin is located at the center of the child div ( ...

What causes old data to linger in component and how to effectively clear it out

Fetching data from NGXS state involves multiple steps. First, we define the state with a default list and loading indicator: @State<CollectionsStateModel>({ name: 'collections', defaults: { collectionList: [], (...), isListLoading: true, ...

Update the display using a button without the need to refresh the entire webpage

I am currently working on a website project that requires randomized output. I have successfully implemented a solution using Javascript, but the output only changes when the page is reloaded. Is there a way to update the output without refreshing the en ...

How can we handle multiple asynchronous calls within a function?

In the process of developing a dynamic page with heavy AJAX interactions that update values in selectors based on prior selections. Currently, working on implementing a "repopulate" feature to fill in selectors based on previous entries. Whenever Selector ...

The data stored in a FormGroup does not automatically transfer to FormData

I am currently facing an issue with uploading multi-part data to my API. To achieve this, I have created a FormData object for the upload process. Initially, I gather all the necessary user input data such as an image (file) and category (string). These va ...

Generate a custom query using user inputs

Let's say I am conducting a search in the database: router.post('/searchLoads', ensureAuthenticated, async (req, res) => { var{ agentCode, loadNumber, pickupNumber, pickupDate } = req.body}); The user does not have to complete all field ...

Tips for preserving a blob file and utilizing it with wavesurfer

I'm currently developing a chat platform that allows users to send audio messages. During the development process, I encountered some challenges when trying to create blobs using react-mic. I'm wondering if it's possible to stringify the b ...

How can eval() be effectively replaced in JavaScript?

Having trouble with javascript eval()? I've encountered bugs and decided to replace all instances of it. Here's an example of what I've changed: var abc = "item." + str3 + ".power"; abc = eval(abc); Now, it's been updated to: var abc ...

One project is experiencing difficulties loading the javascript resource file, while in another project, the file is successfully

I have encountered a puzzling issue with two identical ASP.net web application projects: the javascript resource file is not loading in one project, while it loads successfully in the other. I am struggling to understand why this disparity exists and how t ...

Configuring Chart.js in Laravel to Initialize with Value of Zero

I'm struggling to set my Chart.js chart to zero in my Laravel project. Could someone please help me with this? $chartjs = app()->chartjs ->name('lineChartTest') ->type('bar') ->size(['width' => ...

Is it possible to enable the position:sticky property to function within an iframe by synchronizing it with the scrolling of the parent document

One challenge I'm facing is ensuring that the <footer> within an <iframe> remains sticky at the bottom, even when the <iframe> doesn't have a scrollbar. This should be based on the scroll behavior of the parent document. Import ...

React components can be used to dynamically render and display an array of objects through methods like reduce and

Here's the scenario at hand: (https://codesandbox.io/s/8p21n6p09l) I have an array of objects (referred to as modules) structured like this: const modules = [ { thematicArea: "Topic 1", id: 1, name: "Building assertive attitude", d ...

Tips for creating a mirrored iframe without the need to load the URL twice: CSS does not trigger the desired effect

I have a unique requirement for two iframes - I want only the first iframe to load a specific URL. Once the first iframe finishes loading, I need the second iframe to display the same content without actually loading the URL again. Here is the approach I h ...

Is it possible to incorporate HTML content into the metadata within the head section of a Nuxt application?

Received HTML content from the backend that needs to be incorporated into the meta tag of the HTML head using nuxt. Encountered an error when attempting to display the received content View Error Outlined below is the code implementation: Snippet of Code ...

Choosing a button element in Node.js using WebDriver-Selenium

On my html page for posting data to the server, I am attempting to automate a specific job by selecting a particular button. However, when using Selenium to select the "text2" button, I am encountering issues. <div id="cdk-overlay-17" class="cdk-ove ...

Error encountered during installation of Webpack and webpack-dev-server

I'm currently working on setting up Webpack and Babel for utilizing React without Create React App (CRA). While trying to install webpack-dev-server, I encountered some dependency issues. PS C:\Users\Lebedev\Desktop\projects\ ...

Utilizing a dynamic form action connected to an Express route

I've been grappling with creating an HTML form in my nodejs application that directs to the appropriate express route upon submission. After researching online, I stumbled upon a potential solution as outlined below: <script> $('#controlPa ...

When attempting to call a recursive method in Vue with a changing `this` object, an error is thrown: "RangeError: Maximum call stack size exceeded"

Update integrate codePen into the project. https://codepen.io/jiaxi0331/pen/xxVZBMz Description encountered an issue while trying to call the parent method recursively Code export default { methods: { dispatch(componentName, event, value) { ...

Accessing elements from an array and performing addition on those that are numerical

I am trying to figure out how to extract the values from an array created by some code and then combine them into a single variable: var selector = 'input[name^="Textbook"]'; $(selector).on('click', function() { ...

Loop through an array using a Meteor template

js if (Meteor.isClient) { Template.body.helpers({ fixtures: function () { Meteor.call("checkTwitter", function(error, results) { return results.data.fixtures; }); } }); } if (Meteor.isServer) { Meteor.startup(function ...