Retrieving information from AngularJS modal window

Seeking a solution to retrieve data FROM modal to invoking controller, as most examples only cover sending data TO the modal.

What is the proper method for achieving this?

Here is the form used within the modal:

<form class="form-horizontal">

<div class="modal-body">

    <div class="control-group">
        <label class="control-label">Name:</label>
        <div class="controls">
            <input type="text" ng-model="transaction.name" placeholder="Transaction name" />
        </div>
    </div>

    <div class="control-group">
        <label class="control-label">Category</label>
        <div class="controls">
            <input type="text" ng-model="transaction.category" placeholder="Category" />
        </div>
    </div>

    <div class="control-group">
        <label class="control-label">Amount</label>
        <div class="controls">
            <input type="text" ng-model="transaction.amount" placeholder="Amount" />
        </div>
    </div>


    ... (other input fields) ...


</div>

<div class="modal-footer">
    <button type="button" class="btn pull-left" data-dismiss="modal">
        <i class="icon-remove"></i>&nbsp;&nbsp;Cancel
    </button>
    <button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction()">
        <i class="icon-ok icon-white"></i>&nbsp;&nbsp;Save Changes
    </button>
</div>

Controllers involved are:

moneyApp.controller("TransactionController", function($scope, $http, $modal, $log) {
console.log("modal: ", $modal);
$scope.transaction = {}
$scope.open = function() {

    var modalInstance = $modal.open({
        templateUrl: 'partials/modal.html',
        controller: 'ModalInstanceController',
        resolve: {
            transaction: function() {
                return $scope.transaction;
            }
        }
        });

    modalInstance.result.then(function (receivedTransaction) {
        $scope.selected = receivedTransaction;
        console.log("Transaction received: ", transaction);
    }, function () {
        $log.info('Modal dismissed at: ' + new Date());
    });

};

$http({method: 'GET', url: 'transactions/15/all/'}).success(function(data) {
    $scope.transactions = data; // response data
});
})

and

moneyApp.controller("ModalInstanceController", function($scope, $modalInstance, $http,     transaction) {
$scope.createTransaction = function() {

    console.log("Transakcja: ", $scope.transaction);
    $scope.transaction.budgetId = 15;
    $scope.selected = {
        item: $scope.transaction
    }
    $http({method: 'POST', url: 'transactions/add/', data : $scope.transaction, headers:{'Accept': 'application/json', 'Content-Type': 'application/json; ; charset=UTF-8'}}).success(function(data) {
        console.log("Transaction succesfully added to a DB...");
    });
}


$scope.ok = function () {
    $modalInstance.close($scope.selected.item);
};

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

Encountering an issue where $scope.transaction is undefined when attempting to invoke createTransaction method. How can I properly retrieve data from this form?

Answer №1

It appears that in order to properly utilize the transaction object in your ModalInstanceController, you must assign it to $scope.transaction. Simply passing in the transaction object is not sufficient; you need to explicitly include it within the scope.

Make sure to incorporate the following line of code: $scope.transaction = transaction

Answer №2

Ensure that in your Modal form, the ng-model object (i.e., transaction) is passed to the function createTransaction() which is triggered upon form submission.

<button type="submit" class="btn btn-primary" ng-disabled="pwError || incomplete" data-dismiss="modal" ng-click="createTransaction(transaction)">
        <i class="icon-ok icon-white"></i>&nbsp;&nbsp;Save Changes
</button>

In your controller, remember to include the object as a parameter in the JavaScript function.

$scope.createTransaction = function(transaction) {

    console.log("transaction details: "+ transaction.category+"  "+transaction.amount);
};

If you encounter any difficulties, feel free to reach out to me for assistance. I can provide you with my working code example.

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

What is the best way to fix the "Module not detected: Unable to locate [css file] in [directory]" error when deploying a Next.js website on Netlify?

Trying to deploy my site on Netlify from this GitHub repository: https://github.com/Koda-Pig/joshkoter.com, but encountering an error: 10:02:31 AM: Module not found: Can't resolve '../styles/home.module.css' in '/opt/build/repo/pages&ap ...

Can Jquery be used to swap out specific li content?

<div class="widget_ex_attachments"> <ul> <li> <i class="fa fa-file-word-o"></i> <a href="uploads/2014/09/Parellel-universe.docx">Parellel universe</a> </li> ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...

Unable to upload the file using AJAX

Here is my AJAX request where I am attempting to send form data to a PHP page and display messages accordingly. The problem I'm encountering is that when using serialize() method in AJAX, my file data is not being posted. As a result, the send.php scr ...

Having trouble editing a form with React Hooks and Redux?

Seeking assistance with creating an edit form in React that utilizes data stored in Redux. The current form I have created is displaying the values correctly, but it appears to be read-only as no changes are being reflected when input is altered. Any advic ...

Error: The method `push` within the `useHistory` function is causing an issue and is currently undefined

Whenever the home button is clicked, I need it to redirect to the homepage '/ '. However, I keep encountering this error. Any suggestions on what steps I should take to resolve this? : import { Route, useHistory } from 'react-router-dom/cjs/ ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

What is the method for changing the icon color to dark in Twitter Bootstrap?

I am facing an issue where the icon in my menu tab turns white when active, making it difficult to see. Is there a way to change the color of the icon to black? I have found a class icon-white to make it white, but there is no corresponding class to make ...

JS issue: Having trouble accessing the array values despite the array being present

I am working on an ajax call where I save the success data in an array. However, when I try to access that data outside of the ajax function and use console to log my array, it appears as expected. Here is a glimpse at what I see on the screen: https://i ...

In order to display the user's identification when a button is clicked using Vue3, I have implemented a function called printName

<td class="one-third column" v-for="user in users" :key="user._id"> <div> <v-btn @click="printIdOrName(user)" height="50" size="large" co ...

Retrieving the value of the selected item when it is changed

I am currently using v-select/v-autocomplete in my project: <v-autocomplete v-modal="newRole" :items="roles" label="--Change role--" required return-object item-value="id" item-text=&qu ...

What is the process by which photoswipe applies styles to blur an image upon clicking the share button?

If you want to see an example, check out this link: http://codepen.io/dimsemenov/pen/gbadPv By clicking on the Share button, you'll notice that it blurs the image (and everything else). Despite inspecting it closely, I still can't seem to figu ...

Leverage access tokens in React.js frontend application

After successfully creating an authentication API using Nodejs, Expressjs, MongoDB, and JWT, I am now working on a small frontend application with React-js specifically for Sign-up and Sign-in functionalities. While I have managed to integrate the Sign-up ...

Node.js: Issues with using async await inside a map function

Currently, I am in the process of developing a clone of Tinder. My focus right now is on working on the match/post request within my backend code. This request involves calling a separate function named match, which is triggered after the current user ha ...

What is the process for utilizing GruntFile.coffee and package.json to extract or create the Lungo.js example files?

I want to experiment with the Lungo.js examples found here: https://github.com/tapquo/Lungo.js. However, when I try to run the index.html in the example directory, it seems like the components and package directories are empty. Although these directories d ...

How can I achieve a fade-in effect whenever the flag image is clicked?

A unique "international" quotes script has been created, showcasing Dutch, English, German, and French quotes. The script displays different quotes every day, with a draft-result visible in the upper right corner of this page ... The code used for this sc ...

What is the method for pulling information from MySQL and presenting it on a website using Node.js?

Currently, my goal is to retrieve data from MySQL and showcase it on my HTML page. The code snippet in server.js looks like this: const path = require('path'); const express = require('express'); const bodyParser = require("body-pa ...

What's preventing me from using just one comparison condition in TypeScript?

The issue at hand is quite simple: An error occurred because I tried to compare a number with a 'Ref<number>' object. It seems ridiculous that I can't compare two numbers, but as I am new to Typescript, I would greatly appreciate some ...

AngularJS 1 scripts being compiled by Gulp in the wrong sequence

Have you ever encountered this issue before? Whenever I run my scripts through GULP, the console starts throwing errors, indicating that my directives and/or controllers are not being registered properly. To address this, I experimented by adding the app v ...