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

Is there a way to load all movies in advance when none of the tags are selected?

In my current project, I am working on a feature that involves an array of movie objects. Each movie has a name and tags assigned to it. I want to be able to display movies based on the tags selected by the user. For example, if the user selects the tag "c ...

Testing an Angular service with dependencies on AngularJS services

I need help transitioning my angular js services to a new angular 7 app. The problem is, these services have dependencies on other angularjs services and I can't convert them all at once while still adding new features. How can I inject angular js ser ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

retrieve a string from a given array

I need to retrieve a string from an array in vue and display it on the screen. Here is the method I created for this purpose: displayFixturesName() { const result = this.selectedFixture.toString(); document.getElementById(& ...

What is the process for setting up URL parameters in Express JS?

I am working on creating an URL that can accept a query after the "?" operator. The desired format for the URL is "/search?q=". I am wondering how I can achieve this in Express JS, and also how I can integrate the "&" operator into it. ...

Assistance with organizing date schedules using Javascript

I'm currently assisting a friend with his small project, and we've run into an interesting situation. Imagine a scenario where a doctor informs their patient that starting today, they have X number of consultations scheduled for every Wednesday a ...

Struggling to get a package running in Next.js that is functioning perfectly in ReactJS

Link I have integrated the JSME React npm package into my application to utilize the JSME editor. While this package works seamlessly in a ReactJS environment, I am encountering issues when trying to use it in a Next.js project. I am receiving an error mes ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

How can I interpret a string with a specific format using JavaScript?

Input String: var json_data = "{0:'apple', 1:'bannana', 2:'guava'}"; Desired Output after parsing with JavaScript: var json_data = { columns: [{0:'apple'}, {1:'bannana'} ,{2:'guava'}] ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

ReferenceError: 'exports' is undefined in the context of Typescript Jest

I'm currently delving into unit testing with jest and encountered an error that looks like this: > npm run unit > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771f181012374659475947">[email protected]</ ...

Use ng-repeat to display data in two separate rows

<tr ng-repeat=x in y> {{X. row data}} </tr> displaying first-row-data at index 0, then showing partial data from second row at index 1 followed by remaining data at index 1 Is it possible to achieve this format? Such as displaying rep ...

Guide on implementing jQuery Validation plugin with server-side validation at the form level

Does anyone have a suggestion for how to handle server-side validation errors that occur after passing the initial client-side validation on a form? $("#contact_form").validate({ submitHandler: function(form) { $.ajax({ type: 'POST', ...

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

Refresh the page once the function has been executed

Recently, I came across a basic javascript code that I need some help with. I want to reload the page after certain elements have faded out and back in. The problem is, I'm not sure where exactly I should include the window.location.reload(); function ...

What are the alternative methods to execute a React.js application without using react-scripts?

After creating my React.js app using the command below: npx create-react-app my-app I'm now looking to modify the package.json script section to run the app without react-scripts. How can I achieve this? "scripts": { "start&quo ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

Using JavaScript or TypeScript to locate the key and add the value to an array

My dilemma involves an object structured as follows: [{ Date: 01/11/2022, Questionnaire: [ {Title: 'Rating', Ans: '5' }, {Title: 'Comment', Ans: 'Awesome' } ] }, { Date: 01/11/2022, Questionnaire ...

Transforming this Rails form into an Ajax/JavaScript/jQuery format will eliminate the need for submission

I have developed a form in Rails that computes the Gross Profit Margin Percentage based on an input of Price. When a user selects the relevant product on the form and enters a price in the 'deal_price' field. A callback is triggered to retrieve ...

a guide to structuring REST API requests with axios in Vue.js

In my Vue.js app, I am utilizing Axios to consume a REST API. Each time I make an API call, I create a new instance of Axios with the necessary authentication headers by calling axios.get in various places. // UserdataComponent.vue const anInstance = axio ...