Invoke the function defined within a modal when dismissing a ui-bootstrap modal

Inside my ui-bootstrap modal controller, I have a $watch function set up for a variable. The code snippet looks like this:

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

        var unregister = $rootScope.$watch(function () { return $rootScope.someVariable; },
                          function (newVal) {
                              if (newVal == false) {
                                  $scope.closeModal();
                              }

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

When I dismiss the modal, I want to ensure that the $watch is unregistered. This works fine when using ng-click="closeModal()" in the HTML. However, it does not work when dismissing the modal by clicking outside of it or pressing ESC. Is there a way to call the unregister function on dismissal? I am aware of modal.result.then(close(),dismiss()); but I prefer not to include unnecessary functions in the parent $scope.

Answer №1

To enhance the functionality, simply include an additional callback to the result promise using unregister:

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

    var unregister = $rootScope.$watch(function () {
        return $rootScope.someVariable;
    }, function (newVal) {
        if (newVal == false) {
            $scope.closeModal();
        }
    });

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

    $modalInstance.result.then(null, unregister);
}]);

By including unregister, it will trigger the callback when either closeModal is executed or the escape key is pressed. Alternatively, you could eliminate $scope.closeModal and utilize ng-click="$dismiss('cancel')" in the template instead.

Answer №2

First things first, it's not recommended to store important data on the $rootScope, especially a watched variable for closing a modal. What specific issue are you attempting to address (and what kind of user experience do you aim to achieve) by relying on a watched variable to close your modal? This approach raises concerns and suggests that there may be flaws in your initial design.

Additionally, your comment about avoiding the resolved promise appears confusing. When you invoke $modal.open(options), you receive an object (let's call it modalInstance) onto which you can then execute your promise callback. Therefore, the promise callback operates within the same context as your modalInstance and any accompanying information provided via options.

For proper utilization of the $modal service, please refer to our documentation available here for detailed examples.

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

Exploring MeanJS through the WebStorm debugger

Currently, I am in the process of developing a node/angular application using the MeanJS project as my foundation. One particular issue that I have encountered involves the grunt file included in MeanJS, which executes a series of tasks prior to initializi ...

How does a browser decide to load content from an http URL when the frontend source is using an https URL?

When using my Vue component to load external content in an iframe, everything works fine locally. However, once I deploy it to my HTTPS site, I encounter an issue. <iframe src="https://external-site" /> Upon deployment, I receive the following erro ...

Can the execution of a jQuery Timeout function be halted if a user navigates away from the page?

Implementing a timer in a view with jQuery: var timer, myDiv = $('#mydiv'); $(document).on('mousemove', function(ev) { var _self = $(ev.target); clearTimeout(timer); if (_self.attr('id') === 'mydiv' || ...

Express JS backend causing CSS file to fail to load in React project

After doing some research on Stack Overflow, I came across a few solutions but none of them seemed to work for my specific situation. I am currently attempting to serve my React website from an Express backend server. Here is the layout of my folders: cli ...

What steps should I take in order to ensure that NPM commands run smoothly within Eclipse?

I have a functional workflow that I'm looking to enhance. Currently, I am developing a JavaScript library and conducting smoke tests on the code by using webpack to bundle the library and save it to a file that can be included in an HTML file for test ...

AngularJS: How to track the number of redirects within an iframe?

Is there a way to track the number of times an iframe redirects using AngularJS? I have tried implementing this code, but it hasn't been successful. I have come across a solution using jQuery mentioned here. Any assistance on this matter would be h ...

Navigating a variety of page styles and views in Angular 1 using routing

Following a tutorial, I have set up code that routes to various pages related to the main type of document used in the application: angular.module('loc8rApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']); function ...

Troubling inconsistency in jQuery's .css function performance

I'm facing a problem with the jquery .css function. I am using it to retrieve the actual height of elements that have their height set to auto. The code I am currently using is as follows: $(this).css({ height: $(this).css("height"), width: $(this).c ...

What could be the reason behind the malfunction of this jQuery post request?

I am currently studying AJAX with jQuery, but I am facing an issue with my registration system. The following code does not seem to work: $('#submitr').click(function () { var username = $('#usernamefieldr').val(); var password ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Can someone help me figure out how to make my Dropdown stay open when I highlight input, drag, and release

While working with the react bootstrap Dropdown component, I've encountered a specific behavior that is causing some trouble. To better illustrate the issue, I've attached some images. In my dropdown, there is an input filter box along with a li ...

Using the hover event in a jQuery plugin: A step-by-step guide

A star rating plugin I am developing is encountering an issue with implementing the hover event. jquery, (function($){ $.fn.extend({ rater: function(options) { var defaults = { } var options = $.exten ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

Sharing methods between two components on the same page in Angular can greatly improve code efficiency

On a single page, I have two components sharing some methods and properties. How can I utilize a service to achieve this? See the sample code snippet below... @Component({ selector: 'app', template: '<h1>AppComponent1</h1>' ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Sending confidential data from the view to the controller without relying on form submission

I am looking for a way to pass a hidden field from a view to a controller. Inside index.chtml <div id="root"> ................ @Html.Hidden("HProjectTypeId", "somevalue") </div> The above code snippet is not enclosed within any form tags ...

NodeJS: The functionality of my node files relies on the variables defined in another file

For my nodejs app, I have created a script called app.js that serves as the entry point. This script initializes both the expressjs app and the http server. To clarify: The modules mentioned are not npm modules; they are custom files that I have written m ...

Loading Google API using AngularJS

Having trouble integrating the Google API into my AngularJS 1.3 application (Single Page Application using ui.router). Following the Google API instructions, I included a reference to the client.js file with a callback in the head section of my index.html, ...

Unable to display array retrieved from successful http get request on the webpage

I've been struggling to output the result from the success function in this specific way, but unfortunately, I haven't had any success. The code works fine when it comes to returning values for UpcomingEvents and displaying them in HTML, but when ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...