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

The parameter '{ validator: any; }' cannot be assigned to the ValidatorFn type in this context

I am currently experiencing a challenge while attempting to create a custom validator using Angular. I have created a form for my sign-up page and wanted to ensure that the password and confirm password fields match by implementing a custom validator. Des ...

Efficiently Extracting Information from JSON Objects

Currently, I am in the process of parsing a JSON file. Let's assume that the JSON data looks like this: {"data" : [ {"ID":12, country: "UK"}, {"ID":13, country: "USA"}, {"ID":14, country: "BRA"}, ]} Instead of just having three entries as show ...

what's causing the tabs in bootstrap to malfunction

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootst ...

Organize data by multiple criteria using List.js

Attempting to configure the list.js plugin to allow sorting based on multiple values. Specifically, the goal is to sort by category first and then alphabetically by title within each category. See a demo here: http://jsfiddle.net/8E7cH/ This functional ...

When using Ionic, clicking on a Google Maps marker to navigate to another page with NavController can sometimes result in the clicks on the new

Upon successfully displaying the pushed page, I encountered a strange issue where all elements with a (click)='doSomething()' binding stopped working throughout the newly loaded page. Additionally, there was an ion-slides element on the pushed pa ...

Extremely sluggish pagination in JQGrid following the implementation of a filter through the filter toolbar

I've encountered a problem while using jqGrid with LOAD ONCE and client-side paging. The addition of a filter toolbar has significantly slowed down the paging process after applying any kind of filter. $(gridElement).jqGrid({ postData: post, ...

The jQuery AJAX response consistently comes back empty

Hello, I'm currently working on creating an HTML form and I need to validate it before submitting the form action. However, when I use AJAX to respond, I keep receiving a blank message. Can anyone help me with this issue? $(function(){ $("#ajax-p ...

Browsing a container with JavaScript

I am attempting to display one div at a time and scroll through them repeatedly. I found and modified a Fiddle that works as intended, but when I try to implement it on my own test page, the divs do not scroll as expected. Here is the Fiddle example: http ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Capture a screenshot of an element in either jpg or png format and proceed to save it to your device using Javascript

I am looking to create a JavaScript function that can capture a screenshot of an element and then allow the user to download it. <body> <h1>Sample text</h1> <h2>Sample text</h2> <table width="1080px" height=" ...

Creating an infinite loop animation using GSAP in React results in a jarring interruption instead of a smooth and seamless transition

I'm currently developing a React project where I am aiming to implement an infinite loop animation using GSAP. The concept involves animating a series of elements from the bottom left corner to the top right corner. The idea is for the animation to sm ...

Wrapping dynamic page titles with comment tags in NextJS for cleaner code

I am currently working on NextJS version 12. In my project, I have a file named Layout.js which contains the following code: import Head from "next/head"; const Layout = ({children, pageTitle, mainClass}) => { return ( <> ...

How to access variables with dynamic names in Vue.js

I'm curious if it's possible to dynamically access variables from Vue’s data collection by specifying the variable name through another variable. For instance, consider the following example: Here are some of the variables/properties: var sit ...

Using the Google Picker API to dynamically load a file picker when needed

I am interested in integrating the Google Picker API. The provided example demonstrates the picker being loaded upon page load, but I would like the picker to load when a specific action is taken, such as clicking on a button. However, implementing this be ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...

Warning: The current version of graceful-fs (3) is deprecated in npm

I encountered an issue while running npm install. I attempted to run the following command before updating: $npm install npm, and also updated graceful-fs. $ npm install -g graceful-fs <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Formik's handleChange function is causing an error stating "TypeError: null is not an object (evaluating '_a.type')" specifically when used in conjunction with the onChange event in DateInput

When using the handleChange function from Formik with the DateInput component in "semantic-ui-calendar-react", I encountered an error upon selecting a date. https://i.stack.imgur.com/l56hP.jpg shows the console output related to the error. AddWishlistFor ...

I'm struggling to find the perfect configuration for Vite, JSconfig, and Aliases in Visual Studio Code to optimize Intellisense and Autocomplete features

After exclusively using PHPStorm/Webstorm for years, I recently made the switch back to Visual Studio Code. The main reason behind this decision was the lightweight nature of VSCode and its widespread availability as a free tool, unlike paid services. I s ...