The step-by-step guide on passing arguments and fetching results from Angular UI Bootstrap Modal through Components

I am facing a simple scenario where I have defined a modal as a component and opened that modal using `uiModal.open`. However, when I try to pass custom data to the modal using "resolve" in the open method and arguments in the controller constructor, the data is not being passed. Additionally, attempting to inject `$uibModalInstance` results in an error: Unknown provider: $uibModalInstanceProvider <- $uibModalInstance. This prevents me from returning the results upon closing the modal.

Custom Template:

<div class="modal-header">
    <h3 class="modal-title" id="modal-title">Modal</h3>
</div>
<div class="modal-body" id="modal-body">
    Some text
        <div class="row">
            <div class="col-sm-10">
                    <textarea class="form-control" name="closureNotes" rows="6" data-ng-model="vm.closureNote" required>
                    </textarea>
            </div>
        </div>

</div>

<div class="modal-footer">
    <button class="btn btn-default btn-close" type="submit" ng-click="vm.ok()">Close Exception Request</button>
    <button class="btn btn-danger" type="button" ng-click="vm.cancel()">Cancel</button>
</div>

Component Setup:

import template from './closeExceptionModal.html';
import controller from './closeExceptionModal.controller';

let closeExceptionModalComponent = {
  restrict: 'E',
  bindings: {
        resolve: '<',
    close: '&',
    dismiss: '&'
    },
  template,
  controller,
    controllerAs: 'vm'
};

export default closeExceptionModalComponent;

Controller Logic:

class CloseExceptionModalController {

  constructor() {
         //Need to retrieve some data from caller here
    }

    ok() {
        this.close(); //Need to return result to caller using `modalInstance.close`
    }

    cancel() {
        this.dismiss();
    }
}

export default CloseExceptionModalController;

Caller Controller Code:

//Need to pass data to modal
let modalInstance = this.$uibModal.open({
    animation: true,
    component: 'closeExceptionModal',
    appendTo: angular.element(document.body),
})

modalInstance.result.then( (result) => {
    alert(result); //This should be the result data from the modal
}, () => {
});

Answer №1

After dedicating nearly three hours to researching the issue, I experimented with passing $modalInstance, $uibModalInstance, and more. I delved into resolve and constructor arguments, scouring numerous threads on stackoverflow, each offering no solutions beyond suggesting upgrades to ui.bootstrap, angularjs, etc.

At the heart of the problem is my attempt to use a component to define a modal instead of inline defining the controller and template within the code of the "caller" controller in a different way.

Armed with bits of knowledge gathered from various threads, I arrived at a simple and effective solution.

To pass data to a component-based modal and modalInstance, all we need to do is update the component definition bindings section:

import template from './closeExceptionModal.html';
import controller from './closeExceptionModal.controller';

let closeExceptionModalComponent = {
  restrict: 'E',
  bindings: {
        resolve: '<', //allows passing data from caller constructor
    modalInstance: '<', //modalInstance will be automatically injected
    close: '&',
    dismiss: '&'
    },
  template,
  controller,
    controllerAs: 'vm'
};

export default closeExceptionModalComponent;

The modal call should resemble this:

let modalInstance = this.$uibModal.open({
    animation: true,
    component: 'closeExceptionModal',
    appendTo: angular.element(document.body),
    resolve: {
        modalData: function() {
            return "test";
        }
    }
})

modalInstance.result.then((result) => {
    alert(result);
}, () => {
});

Here is how my final modal controller looks:

class CloseExceptionModalController {

  constructor() {
        this.$ctrl = this; //storing the controller instance

        console.log(this.$ctrl.resolve.modalData); //input data here
    }

    ok() {
        //modal instance auto-injected, allowing us to call close and pass the result
        this.$ctrl.modalInstance.close(this.closureNote);
    }

    cancel() {
        this.dismiss();
    }
}

export default CloseExceptionModalController;

I trust that this information will assist others navigating the challenges of utilizing the ui bootstrap modal with components for data passing and retrieval! :)

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

A guide to resetting items directly from a dropdown select menu

I need help with clearing or resetting select options directly from the dropdown itself, without relying on an external button or the allowClear feature. Imagine if clicking a trash icon in the select option could reset all values: https://i.stack.imgur. ...

What is the reason for the absence of a field display when using curly braces to reference a variable that contains an array?

Within the code of my company, I came across the following: test.active = []; test.active.$selectedRow = null; I am curious if this is considered a valid practice. While it functions properly, it strikes me as unusual for an array to have a field within ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...

Utilize AJAX JQuery to Transmit POST Data

I am facing an issue with sending the selected item from a Bootstrap dropdown to my controller using the POST method. Unfortunately, I am encountering difficulties in getting it to work. Within the dropdown, I am fetching records from the database and dis ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

How to apply CSS styling to a specific element using jQuery

When using $(".className"), all elements with the class .className are returned. How can I target a specific element by its index number to apply styling only to that element? <html> <head> <script src="https://ajax.googleapis.com/ajax ...

A numeric input area that only accepts decimal numbers, with the ability to delete and use the back

I have successfully implemented a code for decimal numbers with only two digits after the decimal point. Now, I am looking to enhance the code in the following ways: Allow users to use backspace and delete keys. Create a dynamic code that does not rely o ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

The content within the tab is currently being loaded

Incorporating jQuery UI tabs into my webpage, I encounter a delay of 5-6 seconds when clicking on a tab as it triggers an ajax call for preparing and displaying content. The screen stays idle during this time, leading to user confusion. I am seeking a sol ...

Navigate to a precise point in a video using react hooks in videojs

I am currently working on adding a feature that allows users to skip forward or backward by 15 seconds in a video. However, I am encountering difficulties when it comes to updating and setting the current time accordingly. const videoNode = useRef(null); ...

Kendo Template Function: Angular JS version 1.6

I'm working with a currency column that looks like this: { field: 'INVOICE_AMOUNT_ORIGINAL', title: $translate.instant('invoiceAmount'), format: '{0:n}', template: '#= currency(dataItem.INVOICE_AMOUNT_ORIGIN ...

Analyzing the audio frequency of a song from an mp3 file with the help of HTML5 web audio API

Currently, I am utilizing the capabilities of the HTML5 web audio API to detect when a song's average sound frequency drops below a specific threshold and create corresponding markers. Although I have successfully implemented this using AudioNodes, th ...

Using the value from the Vuex state to set the initial value for a different parameter

I am facing an issue with utilizing an array of objects in my Vuex state to set a default value for another parameter, specifically for mainAccount: For instance: const store = new Vuex.Store({ state: { AccountNums: [ { label: 'M ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

Exploring the world of Node.js with fs, path, and the

I am facing an issue with the readdirSync function in my application. I need to access a specific folder located at the root of my app. development --allure ----allure-result --myapproot ----myapp.js The folder I want to read is allure-results, and to d ...

What is the function of the "angularCompileRows" option in ag-grid?

Today, I spent time trying to trigger ng-click events on individual cells within an ag-grid, aiming to call a method in the parent controller. Despite numerous attempts, the solution eluded me until I stumbled upon some advice from other developers who men ...

Whenever I attempt to click on a Teaxarea, it automatically collapses and prevents me from typing my comments

After crafting my code on this link, I created three directives, each responsible for collapsing certain elements. Upon running the code, you will notice two panels where clicking on the address collapses it, and clicking on the comment also collapses it. ...

Transferring information between controllers using AngularJS

I have two controllers and I am trying to send data from the first one to the second one without using a factory. module.controller('UpdatesController', function ($scope) { var update = {}; update.items = [{ title: 'Comp ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

There are multiple sets of radio buttons within nested ng-repeats, but only the final group displays the selected value

I am having an issue with updating a form that contains multiple radio buttons based on data retrieved from an API. The challenge is that only the last set of radio buttons displays the value correctly. Below is the code snippet I am using (angular bracket ...