Quick tip on closing an Angular-ui modal from a separate controller

I am currently using Angular-ui to display a modal with a form inside. Here is the code snippet:

app.controller('NewCaseModalCtrl', ['$http', '$scope','$modal', function ($http, $scope, $modal, $log) {

  $scope.items = ['item1', 'item2', 'item3'];
  $scope.open = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'modal-new-case.html',
      controller: 'ModalInstanceCtrl',
      size: size,
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
    });
  };
}]);

Additionally, I have another controller within the modal-new-case.html template. This controller is responsible for sending an HTTP request and then closing the modal. Here's the code for that:

    app.controller('CreateCaseFormCtrl', ['$http','$scope', function($http,$scope) {
    $scope.formData = {};
    $scope.processForm = function() {

        $http.post('http://api.com/proj', $scope.formData).
        success(function(data, status, headers, config) {
            console.log("Success " + data.id);
        }).
        error(function(data, status, headers, config) {
            console.error("Error " + status + data);
        });
    };

}]);

When the modal-new-case.html template is loaded with:

ng-controller="NewCaseModalCtrl"

The corresponding HTML consists of:

<div ng-controller="CreateCaseFormCtrl">
    <form ng-submit="processForm()">
                <button class="btn btn-primary" ng-click="processForm()" >OK</button>
                <button class="btn" ng-click="cancel()">Cancel</button>
    </form>
</div>

To achieve the desired outcome of running the processForm() function and then closing the modal upon success, you can call the "cancel()" function. However, referencing it from the CreateCaseFormCtrl controller might be tricky.

If you have any insights or suggestions on how to tackle this issue, I would greatly appreciate your assistance. Please note that my familiarity with Angular is limited, so a simple and straightforward solution would be preferable even if not ideal for long-term production use.

Answer №1

Step 1: Start by removing the line that contains

ng-controller="CreateCaseFormCtrl"

inside

<div ng-controller="CreateCaseFormCtrl">
    <form ng-submit="processForm()">
                <button class="btn btn-primary" ng-click="processForm()" >OK</button>
                <button class="btn" ng-click="cancel()">Cancel</button>
    </form>
</div>

Step 2: Next, update

controller: 'ModalInstanceCtrl',   =>   controller: 'CreateCaseFormCtrl'

within

var modalInstance = $modal.open({
  templateUrl: 'modal-new-case.html',
  controller: 'CreateCaseFormCtrl', //Add here
  size: size,
  resolve: {
    items: function () {
      return $scope.items;
    }
  }
});

Step 3: Then, in CreateCaseFormCtrl, include a new service named $modalInstance

app.controller('CreateCaseFormCtrl', ['$http','$scope', '$modalInstance', function($http,$scope, $modalInstance) {

Step 4: Add functions for close and ok actions

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

and also add $modalInstance.close(); in

$http.post('http://api.com/proj', $scope.formData).
    success(function(data, status, headers, config) {
        console.log("success " + data.id);
        $modalInstance.close(); //add here
    }).
    error(function(data, status, headers, config) {
        console.log("Error " + status + data);
    });

Answer №2

Refer to the API documentation for using $modalInstance.dismiss method.

Make sure to utilize $modalInstance.dismiss in NewCaseModalCtrl:

controller('NewCaseModalCtrl', ['$scope', '$modalInstance', function ($scope, $modalInstance,

    ...

        $modalInstance.close(data);

Answer №3

This method can be applied universally or from various controllers as well:

// to hide any open $mdDialog modals
  angular.element('.modal-dialog').hide();
  // to hide any open bootstrap modals
  angular.element('.inmodal').hide();
  // to hide any sweet alert modals
  angular.element('.sweet-alert').hide();

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

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...

A comprehensive guide to navigating pages using AngularJS

Greetings! I've recently embarked on my Angular JS learning journey and have encountered an issue with loading content from pages. Unfortunately, I am not able to receive any content. Below are snippets of my index file and corresponding JavaScript co ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...

Ensuring the checkbox is disabled prior to editing

Check out my table below: https://i.stack.imgur.com/7byIa.png Whenever I click the edit button, I can modify the status field and action field. This feature works correctly. However, the issue is that I am able to change the values of status and action e ...

Unable to retrieve the value property from document.getElementById as it is null

Can someone help me with reading the input field value in my code? <input type="text" name="acadp_fields[1200]" class="text" placeholder="" value="December 26, 1969"> Here is the code snippet I am us ...

Session-based Authorization

I'm completely new to working with express.js, and I've been facing an issue while trying to create a session-cookie after logging in. Even though I can initiate the session and successfully log in, the session data doesn't carry over to the ...

Create an animation effect where a div increases in height, causing the divs beneath it to shift downward in a

My aim is to create columns of divs where the user can click on a div to see more content as the height expands. I've managed to set this up, but it seems there's an issue with the document flow. When I click on a div in the first column, the div ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Manipulating classes within ng-class in AngularChanging classes in ng-class dynamically

Featuring multiple elements with an ng-class that behaves similarly to a ternary operator: ng-class="$ctrl.something ? 'fa-minus' : 'fa-plus'" To access these elements, we can compile all the ones with fa-minus and store them in a lis ...

Is it necessary for a click handler to be triggered when clicking on a scrollbar?

Check out these HTML snippets: Jsfiddle <style> div { margin:20px; border: 30px red solid; padding: 20px; background-color:green; overflow-y:scroll; } </style> <div onclick="alert('div clicked');"> ...

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

Having trouble displaying the Chrome context menu for a specific Chrome extension

I've read through several posts on this topic, but I'm still struggling to identify the issue with my implementation of the Chrome contextMenu API. I simply copied the code from a tutorial on Chrome APIs, and though there are no errors, the menu ...

Mobile phone web development using HTML5

I am currently facing an issue with playing sound on mobile browsers. In my code snippet, I have the following: Response.Write("<embed height='0' width='0' src='Ses.wav' />"); While this works perfectly fine on desktop ...

How can you capture the VIRTUAL keyCode from a form input?

// Binding the keydown event to all input fields of type text within a form. $("form input[type=text]").keydown(function (e) { // Reference to keyCodes... var key = e.which || e.keyCode; // Only allowing numbers, backspace, and tab if((key >= 48 && ke ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Connecting Next.js to a Database: A Step-by-Step Guide

I am interested in developing an application similar to Samsung Health that will involve heavy querying on a database. I am unsure whether it would be more beneficial to create a custom server using Node.js (with Express.js) instead of using the integrate ...

Utilize React to update the state of arrays in functional components

Need help with updating the cars array in my React app. When I click on the Add button, a new object is added to the updatedCars array but the state of cars does not get updated. Even after adding a new object to the array, the initial state remains uncha ...

Is it possible to minify HTML in PHP without parsing JavaScript and CSS code?

After finding a solution in this discussion, I successfully managed to 'minify' HTML content. function process_content($buffer) { $search = array( '/\>[^\S ]+/s', // eliminate spaces after tags, except for ...