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

Is there a way to have my code run a script only once right after a component has finished loading?

I am currently developing a web application using Vuejs and implementing the vue-router with single file components. One issue I am facing is that whenever a user navigates to a specific route, the created() function within the component gets triggered. T ...

Creating a custom HTML5 canvas with images from a JSON array

I am currently working on a project to develop a unique slideshow feature by hosting images in an external JSON array and then loading them onto an HTML page. The next step is to insert these images onto an HTML5 canvas. While I have successfully loaded a ...

Changing dimensions of cube on stable base

I'm currently working on a project involving a dynamic cube that can be scaled in real time by adjusting its mesh. However, I'm facing a challenge in keeping the cube fixed to the floor while changing its height. Here's a snippet of the code ...

Unable to modify the content of a table cell after triggering a Bootstrap modal event

Looking to update values in rows of a table? Here is an example table: I need to update the title per selected row. After selecting the first row, changing the value works fine. However, when I choose the second row, the issue arises where the value from ...

Comparison of element state prior to and post editing (with contentEditable)

Exploring how elements within a div can be monitored for changes made by the user (thanks to contentEditable), I created a sample page with the following setup: before_html = $("#example_div").children(); $("#differences_button").on("click", ...

Is it possible to deactivate an element based on a specific string present in the URL?

<div class="custom-class1"> <div class="custom-class2" id="custom-id1">hello 1</div> <div class="custom-class3" id="custom-id2">hello 2</div> <div class="custom-class4" id="custom-id3">hello 3&l ...

Instructions on developing a customized AngularJS email directive that utilizes @something.com as a placeholder and automatically adds it to the user's input

I need assistance with creating a custom email input directive that includes "something.com" as both a placeholder and part of the input. The directive should monitor the user's input until they type '@', at which point it should append what ...

Challenges regarding placement and z-index are causing issues

Currently, I am attempting to make the menu overlap the content on my webpage. However, I am facing an issue where it moves the content box instead of overlapping it. I have already experimented with the position: relative concept, but unfortunately, the ...

Is it feasible to save the outcome of a function call using ng-repeat?

Looking for a solution with the following code: <tbody ng-repeat="term in Items | filter:searchText track by term.Element"> <tr class="term-row"> <td ng-show="!IsValid(term)" class="text ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

Issues relating to the total count of pages in the uib-pagination component of AngularJS

While there is a previous thread discussing a similar topic Calculating total items in AngularJs Pagination (ui.bootstrap) doesn't work correctly, it does not address my specific issue and I am unsure how to contribute to it. We are using a complex s ...

What is the best way to implement an 'onKeyPress' event listener for a <canvas> element in a React application?

I've been working with React for a while now and I understand how its event system functions. However, I've run into an issue where the onKeyPress event doesn't seem to be triggering on a <canvas> element. Surprisingly, it's not w ...

Hide or show list items in an unordered list using jQuery

I am interested in creating a script that can toggle between "show more" and "show less" functionality for elements in a list. I came across this script: HTML <ul id="myList"> <li>One</li> <li>Two</li> <li> ...

Extract information from an array located inside a nested object

My aim is to calculate the length of the skills array for each user individually. To begin, I have this JSON data: const txt = `{ "Alex": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Encountering a 304 status error in the HTTP GET response after deploying a React app on Netlify

After deploying my react application on Netlify, I used the npm run build command to create the local scripts and manually deployed them in production mode on Netlify. The build scripts were generated on my local machine and then uploaded to the Net ...

Change the behavior of JavaScript so that it executes when clicked, not when the

This script is currently set to run when the page loads: <script language="JavaScript"> j=parseInt(Math.random()*ranobjList.length); j=(isNaN(j))?0:j; document.write(unescape(ranobjList[j])); </script> Is there a way I can mak ...

AngularJS ui-grid template for conditional cell

I am struggling to correctly display the text in a cell as either a link or plain text based on the status. If the status is 'Deleted', I want the name to be displayed as plain text, otherwise as a hyperlink. My grid options always show it as a h ...

What is the best way to simultaneously watch multiple properties and interpolate them into a single expression?

How can I watch two input fields - name and text - simultaneously and combine their values into a single expression? Thank you! Last updated on 9/7/2014: Check out this working version of the code on Plunkr :) Kudos to Mohammad Sepahvand! Here&ap ...

I am facing an issue with Angular 14 and Webpack 5, where certain unnecessary nodejs modules seem to be hindering me from successfully serving

I have recently started working on a cutting-edge Angular 14 application. My current node version is v14.20.0, and npm version is 8.17.0. Despite my best efforts, I seem to be facing an issue with multiple nodejs dependencies being included in my project ...

Transform the JSON data to generate a fresh JSON output

I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct. Any assistance would be greatly appreciated. CURRENT ISSUES: [resolved]I am unable to determine why the duration ...