What is the process of transferring data from one div to another div (table) using AngularJS?

In my quest to enhance my table with JSON data upon clicking the + icon, I am faced with two sections: Pick Stocks where stock names and prices (retrieved from data.json) need to be added to the table found in the Manage Portfolio section.

First Section https://i.stack.imgur.com/P839d.jpg

Second Section https://i.stack.imgur.com/BBmbn.jpg My goal is to populate the respective stock name such as ADFI, ALAN, etc., alongside their prices into the corresponding columns of the table in the second section whenever the relevant + icon is clicked. Although I have made attempts at this, I am unsure about the next steps. Thank you. Here is the plunker

             <table>
                <tr>
                    <th>STOCK</th>
                    <th>PRICE</th>
                    <th>SHARES</th>
                    <th>WEIGHT</th>
                </tr>
                <tr ng-repeat="portfolio in portfolios">
                    <td ng-model="portfolio.stockfromdata"></td>
                    <td ng-model="portfolio.pricefromdata"></td>
                    <td>num</td>
                    <td ng-model="portfolio.weightfromprice"></td>
                </tr>
            </table>

Script

 $scope.portfolios = [];

    $scope.addStock = function() {
        $scope.portfolios.push([{
            "key": $scope.portfolio.stockfromdata,
            "value": $scope.portfolio.pricefromdata
            // "weightfromprice": $scope.weightfromprice
        }]);
    };

Answer №1

If you want to display object data in a table and add values by clicking a plus sign, you can use the following code:

$scope.addToTable = function(key, value){
  var mystock={key: value};
    if (!(key in $scope.stocksObj)){
    $scope.stocksObj[key] = value;
    }
}

<tr ng-repeat="(key, value) in stocksObj"><td>{{key}}</td><td>{{value}}</td></tr>

You can view a working example here: https://plnkr.co/edit/b3QECT1pvqnWwyQoEBTb?p=preview

If you need to have more fields for each stock entry, it's better to create an object with properties like key, value, shares, weight, etc and push them into an array. The updated function will be as follows:

$scope.addToTable = function(key, value, index){
  var mystock={};
  mystock.key = key;
  mystock.value = value;
    console.log(index);
    if(indexes.indexOf(index) == -1){
        indexes.push(index);
        $scope.stocksArray.push(mystock);
    }
}

Here's a working example for that: https://plnkr.co/edit/r2WLGakBU9kGmWLWBN7K?p=preview

Answer №2

ng-model directive facilitates a 2-way binding feature, therefore, instead of using

<td ng-model="portfolio.stockfromdata"></td>

consider utilizing

<td ng-bind="portfolio.stockfromdata"></td>
or
<td>{{portfolio.stockfromdata}}</td>

if you wish to enable editing, employ ng-model with an input like

<td ><input ng-model="portfolio.stockfromdata"/></td>

this way, ng-model will connect your data to the input model, any changes in the UI will be reflected back to the JSON bound data in your controller, fulfilling the purpose of ng-model

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

Ways to extract specific data from a Json response

Currently, I am engaged in a school project that involves manipulating json data from the Google Geocoding API. I am facing a dilemma on how to properly store the "formatted_address" (as shown below) from the API response so that I can utilize this inform ...

Tips for ensuring that divs resize to match the container while preserving their original proportions:

#container { height: 500px; width: 500px; background-color: blue; } #container>div { background-color: rgb(36, 209, 13); height: 100px; } #one { width: 1000px; } #two { width: 800px; } <div id="container"> <div id="one">&l ...

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

Is there a problem with the way divs are being displayed when using jQuery to show the first 12 elements with the class "hide-show"?

I am encountering a problem with displaying data using the jQuery slice() and show() methods to reveal dynamically generated divs from a PHP function. The code is as follows: <style> .hide-show { display :none; } </style> <div class="c ...

Using <Redirect/> in ReactJS results in rendering of a blank page

Hello everyone, I've been working on a feature where I want to redirect the user to the home page using <Redirect/> from react-router after they have successfully logged in. However, I'm facing an issue where the timeout is functioning corr ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

`How can I define dependencies and build an npm package?`

I have authored several npm modules, all of which are designed to enhance existing libraries such as three.js or react. While the packages appear to be downloaded, I have not received any feedback confirming whether they have been implemented correctly. ...

Accordions housing Bootstrap 3 pills in a sleek design

I'm working on integrating pills and an accordion in Bootstrap 3. Everything seems to be functioning correctly, but there are a couple of issues I am encountering: When the accordion is open, clicking on another tab closes the accordion. I would li ...

JavaScript code to access values from a JSON object

{ "4": { "structure": "Archaeological Museum", "boxes": [{ "id": "5", "name": "Ground Cassa DEMO" }] }, "5": { "structure": ...

AngularJS - Viewless and Issue-Free

I'm currently working on a project that involves using AngularJS and PHP. I made some changes, but now it's not functioning properly... The issue is that there are no errors in the console, Angular works (I can retrieve its version), but my vi ...

Extracting server error messages on the client side using Node.js

Before storing data in the database, my server performs validation checks. If it is unable to save the data into the database, an error message is sent. In my client-side application, how can I retrieve and display this error message? Below is the HTTP r ...

When making an HTTP GET request followed by another GET request in Express, it results in an error with undefined parameters on the

When I open a form that has a link to a list and try to access the list, I encounter an "id" undefined error for the form we came from, which was already functional. The issue arises when I have a GET page where I present a form to modify a record at /loc ...

Dealing with uncaught promise rejection while using the 'opn' npm package in Docker

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Exited with code 3 I encountered this error while trying to open links using a module within a Docker container. The code functioned fine on my local machine without D ...

What is the best way to ensure that custom JavaScript and CSS files in Sphinx are always loaded with the most recent changes

Within the configuration file conf.py for Sphinx, I have specified the following: html_css_files = ['css/custom.css'] html_js_files = ['js/custom.js'] However, any alterations made to custom.js or custom.css do not immediately appear i ...

Is there a way to dynamically add an option to multiple select boxes and then only redirect the browser if that specific option is chosen using jquery/js?

Presently, this is the code I am working with. The URL validator is specifically included because there was an issue with redirection occurring on any option selected, however, I only want a redirect to happen when the options I add with jQuery are clicked ...

Displaying an array using Javascript that contains variables along with HTML code

First of all, thank you for your help and support! I am struggling with correctly outputting HTML code with variables using jQuery and jQuery Mobile. I receive results from a PHP database, separated by "," and converted into a JavaScript array successfull ...

What is the best method to retrieve checked checkbox values and the selected dropdown value using AngularJS?

My code is set up to capture checked checkbox values and selected dropdown value when the submit button is pressed. It successfully retrieves the checked checkbox values, but I'm having trouble getting the selected offer from the dropdown. For example ...

Navigating the parent scope in Angular using TypeScript

Is there a way to access the parent Controller's scope from within the TypeScript class? Here is the code snippet: export class EntityOverviewCtrl extends AbstractCtrl { public static $inject = ["$state", "$http", "CurrentSession"]; publi ...

What is the proper way to activate speech recognition on electron?

I have a chatbot application running on Electron, and I am in need of implementing speech-to-text functionality. I initially tried using window.SpeechRecognition and window.webkitSpeechRecognition, but it seems like Chrome does not support speech recogniti ...

Tips for delaying the evaluation of an <input> field?

I am interested in analyzing the content of an <input> field when there is no activity from the user. One simple example I have considered is counting the number of characters, but the actual analysis process is very resource-intensive. To optimize ...