What is the process for setting a default value in an array using Angular and then showcasing that value in a textbox?

I have been working on creating a form that includes a feature to dynamically append new rows. While I am able to successfully create new rows dynamically, I am facing an issue with displaying the initial values in my textboxes.

Below is a snippet of my code:

<div class="row" ng-app="product_list">
    <div class="table-responsive" ng-controller="productList">
        <table class="table table-bordered table-hovered">
            <thead>
                <tr>
                    <td class="text-left">Product Name</td>
                    <td class="text-left">Quantity</td>
                    <td class="text-left">Price</td>
                    <td class="text-left">Subtotal</td>
                    <td class="text-center"><button type="button" class="btn btn-default" ng-click="addNewRow()">Add Row</button></td>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="value in product.item">
                    <td class="text-left">
                        <input type="text" ng-model="item.name" class="form-control" />
                    </td>
                    <td class="text-center">
                        <input type="number" ng-model="item.quantity" class="form-control" />
                    </td>
                    <td class="text-right">
                        <input type="number" ng-model="item.price" class="form-control text-right" value="{{ value.price }}" />
                    </td>
                    <td>{{ item.price * item.quantity | currency }}</td>
                    <td class="text-center">
                        <button type="button" class="btn btn-danger" ng-click="removeRow($index)">Remove</button>
                    </td>
                </td>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3">
                    <td colspan="3" class="text-left">
                        <label>Subtotal: </label>
                        <input type="text" class="form-control text-right" value="{{ total() | currency }}" readonly />
                    </td>
                </tr>
            </tfoot>
        </table>
    </div>
</div>

The JavaScript Code:

<script type="text/javascript">

    var appList = angular.module('product_list', []);

    appList.controller('productList', function($scope){

        $scope.product = {
            item: [
            {
                product_name: 'Test name 1',
                quantity: 5,
                price: 99.9,
            }
            ]
        };

        $scope.addNewRow = function() {

            $scope.product.item.push({
                product_name: '',
                quantity: 1,
                price: 0
            });

        }

        $scope.removeRow = function(index) {
            $scope.product.item.splice(index, 1);
        }

        $scope.total = function() {

            var total = 0.00;

            angular.forEach($scope.product.item, function(item){
                total += item.quantity * item.price
            });

            return total;

        }

    });

</script>

Here's the plnkr link for reference: http://plnkr.co/edit/6vAVPw?p=preview

Answer №1

The variables are misaligned, with value being used repeatedly here:

<tr ng-repeat="value in product.item">

However, you also reference the item as item, so simply change value in product.item to item in product.item:

<tr ng-repeat="value in product.item">

Additionally, on line 44 of the HTML there is invalid HTML - switch </td> to </tr>

Another detail to note is that your item variable is named product_name in your objects, but you assign item.name to your ng-model. Make sure to update your first textfield to ng-model=item.product_name

Revised Plunker

Answer №2

The reason for this issue is due to the fact that you have used different variable names in ng-repeat and ng-model

<tr ng-repeat="value in product.item">

Instead of using ng-model="item.name", simply replace value with item

For example:

<tr ng-repeat="item in product.item">

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

Angular.js: Utilizing ng-model for checkboxes

Here's the code for my project: <input type="checkbox" ng-model="variable"> In this scenario, the variable will hold either true or false based on the checkbox status. However, I want it to store "+" instead of true and "-" instead of false. W ...

How can NodeJS implement ThreadLocal variable functionality without relying on req and res.locals?

In a specific situation, I am required to handle business logic and logging for each request separately. This means that the data stored should not overlap with data from other requests. Using res.locals or req objects is not an option in this case becaus ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

Feeling uncertain about Node, NPM, Bower, and how to set them up for Bootstrap?

Looking to expand my knowledge in web development, I have a solid understanding of HTML, JS, CSS, and server-side programming. However, the concepts of Nodejs, npm, and Bower are still unclear to me. In order to begin a new project, I created a designated ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Utilizing async/await as a module function: A comprehensive guide

Express Route: const express=require('express'); const router=express.Router(); const trackRepo=require('../model/track'); router.post('/live',function(req,res){ const time=1439832167; const list=trackRepo.getAlerts ...

How can one effectively access a nested JSON value in Angular by concatenating all fields?

If we have a JSON stored in the variable person like below: { "firstName": "First Name", "lastName": "Last Name", "address": { "city": "New-York", "street": "Some Street" } } To access the value of street, we would typical ...

The background color should only cover a specific percentage of the element

Here is the current structure I have: <li class="myclass" ng-class="myAngularClass"> <div> div1 <div> div2 </div> </div> </li> The li element has dynamic dimensions and width. The class "myAngularClass" i ...

Using Node modules in the browser: A beginner's guide

Once you've used npm to install packages such as: $ npm install bootstrap or $ npm install angular these packages are typically stored in the "node_modules" directory. The question now arises, how do you link to or access them from an HTML page? U ...

A Step-by-Step Guide to Setting Up and Utilizing V-Calendar in Vue.js

I am currently trying to incorporate the V-Calendar library into my Vuetify application. Up until now, the app was working fine, but I seem to have hit a roadblock with the correct installation of the V-Calendar library. Although no error messages are bei ...

gathering information from a group of items and organizing them into a fresh set of items

I have a collection of objects called Lines nestled within the rows array, which is nested within the tabs array. My goal is to extract specific data from the lines array and transfer them into a new array named 'colors'. This is how the initial ...

What could be causing the sudden disappearance of the button?

There is an element with the ID "alpha" that contains the text "Now I'm here...". When the button is clicked, only the text should be removed, not the button itself. <div id="alpha">Now I'm here...</div> <button type="button" oncl ...

Tips for transmitting variable values through a series of objects in a collection: [{data: }]

How to pass variable values in series: [{data: }] In the code snippet below, I have the value 2,10,2,2 stored in the variable ftes. I need to pass this variable into series:[{data: }], but it doesn't seem to affect the chart. Can anyone guide me on ...

Limiting the invocation of the listener method in f:ajax depending on the return value of onevent

I am looking to check if the Onevent javascript function returns true or false. My goal is to restrict the listener method call based on the return value of the Javascript function. However, the code snippet provided is causing a syntax error in Firebug. ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...

What is the best way to adjust the size of my Leaflet map within a Bootstrap collapse module in my Dash application?

I am currently working on integrating a bootstrap collapse element that contains a leaflet map. My goal is to toggle the map view open and closed, but I have encountered an issue where the map does not resize properly when the collapse item is opened. As a ...

Executing a query with a `has many` relationship in MongoDB: Step-by-step guide

In my setup with Node, Express, and backbone, I am successfully retrieving records from MongoDB collections using simple queries. However, I am struggling to understand how to query more complex data, such as the one below: db.employees.aggregate( [ ...

When attempting to input a value in the middle of the line, the cursor unexpectedly leaps to the end

I have successfully created a code that prevents spaces at the beginning and special characters in an input field. The code is working perfectly, but there is an issue with the cursor moving to the end when trying to type at the beginning or middle of the ...

Steps to obtain an Element binding from a Svelte component

Is it possible to retrieve the bounding client rect of an anchor element? I typically mark this using the syntax bind:this={someVariable}. However, when I add this code to a Svelte component, I receive a different object that Svelte uses to represent a c ...

The socket context provider seems to be malfunctioning within the component

One day, I decided to create a new context file called socket.tsx: import React, { createContext } from "react"; import { io, Socket } from "socket.io-client"; const socket = io("http://localhost:3000", { reconnectionDela ...