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

struggling with beginner-level JavaScript issues

Hey there, I've been running into a bit of an issue with my basic javascript skills: function tank(){ this.width = 50; this.length = 70; } function Person(job) { this.job = job; this.married = true; } var tank1 = tank(); console.log( ...

How can I prevent a repetitive div from appearing in a JQuery show/hide function?

Whenever I trigger my AJAX function, the loading image keeps repeating every time I click on the next page. I want to prevent this repetitive loading image and only display it once when I go to the next page. To address this issue, I created a <div cla ...

Combining JSON fields and searching based on the combined value within MarkLogic

In the JSON format provided below, I have stored a person's first name and last name along with their nickname. { "Person": { "Records": [ { "nameType": "Primary", "firstName": "Sagar", "lastName" ...

Generating references dynamically without the use of strings

UPDATE: Our current React version is 16.2.0, which is important for this question (check out this answer). From what I understand, this is the recommended way to create a ref in our React version: <div ref={(r) => { this.theRef = r; }}>Hello!< ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

The HTML document is unable to locate the Angular framework

I'm encountering an issue with the code below on my HTML page - every time I run it, I receive an error message saying "angular is not defined". I've already included angular in the head section of the page so I'm puzzled as to why it's ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

Can I store a large batch of images in one location and retrieve them using a REST API?

So here's the situation: I currently have a large collection of images saved on my Mac. I'm working on a landing page that resembles an ecommerce deal site. Manually inputting the src url for each of the thousand pictures would be incredibly tim ...

AngularJS modules are not loading dependencies such as constants or controllers

While searching for the reason why a properly defined factory is not loading, I came across this question. This led me to contemplate on the concept of services being "defined in an angular module". Consider this example: angular.module('d3', ...

Is it possible to execute a function once another function has been called within a specific interval

Currently, I am working on a Greasemonkey script and have encountered an issue. The website contains a function that runs at regular intervals: jQuery(function1.run); setInterval(function1.run, function1.interval); I aim to execute my function immediatel ...

Having trouble with Vue.js implementation of Bootstrap tab navigation?

I am currently working on a vue.js application that consists of 2 routed components. I recently attempted to integrate a bootstrap tab navigation into the first component, but unfortunately, the tab contents are not being properly displayed. <templat ...

The ng-model does not reflect changes when using the JQuery datepicker

Currently, I have set up two textboxes for users to choose a date. I am utilizing JqQuery's datepicker UI to showcase a small calendar pop-up whenever the user clicks on the textbox. However, an issue arises when I select a date in the calendar popup ...

What is causing ngdocs to produce zero files?

I have created a basic project to experiment with grunt-ngdocs (https://www.npmjs.org/package/grunt-ngdocs). But, for some reason, when I attempt to generate documentation, it fails to recognize any comments. Why is this happening? Can someone offer assist ...

Storing information as variables in jQuery

I'm fairly new to working with Javascript and JQuery, and I've encountered a challenge that I initially thought would be straightforward. My project involves creating a website consisting of a single HTML page, a CSS stylesheet, and a JavaScript ...

My tests are not passing because I included a compare method in the Array prototype. What steps can I take to fix this issue in either the

Embarking on the challenging Mars Rover Kata has presented a unique problem for me. My jasmine tests are failing because of my array compare method within the prototype. This method is crucial for detecting obstacles at specific grid points. For instance, ...

Observing the data retrieved from an AJAX request

Currently, I have this AJAX call in my code: $('#search').keyup(function() { $.ajax({ type: "GET", url: "/main/search/", data: { 'search_text': $('#search').val() }, suc ...

Ways to eliminate class from HTML code

Trying to detect if a navigational element has a specific class upon click. If it has the class, remove it; if not, add it. The goal is to display an active state on the dropdown button while the dropdown is open. The active state should be removed when a ...

Displaying the second image twice in a jQuery image slider

When attempting to implement a slider on my website, I encountered an issue where the second image appears twice in a row before the slider starts working as expected. I'm struggling to figure out why this is happening. Here is the jQuery code I am u ...

Creating a dynamic image carousel using jQuery

Today, I completed the jQuery course on Code Academy and am now trying to create an image slider using it. While I have a general idea of how it should work, I feel like I'm missing a key element. My goal is to have the slider continuously running whe ...

Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far: <script> var margin = { top: 20, right: 80, bottom: 20, left: 50 }, width = $("#trendc ...