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

Adjust the height of a div using jQuery animate based on the amount of text within

I have created a basic animation feature where users can click on an expanding box. I am looking for a solution that does not involve using a plugin. Currently, the code looks like this: $('#one').css("height", "22"); $('#t1').cli ...

What is the reason for JavaScript consistently returning the initial value as the result?

My current issue involves customizing Joomla article content using a module. I am attempting to hide a div until a user clicks on an input, such as a radio button labeled Test1. Once Test1 is selected, another hidden field within the div should display the ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

What is the process for implementing JavaScript in Django?

I'm a newcomer to this and although I've tried searching on Google, I haven't found a solution. I'm facing an issue where I can include JavaScript within the HTML file, but it doesn't work when I try to separate it into its own fil ...

"I'm receiving the error message 'Unable to authenticate user' when attempting to connect to Supabase through the NextJS tutorial. What could be the

Recently, I embarked on a new project using NextJS and Supabase by following the tutorial available at this link. After completing the initial setup by updating the ".env.example" file to ".env.local" with the Supabase credentials, including creating a ne ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

A problem arises when trying to showcase the content in a responsive manner on the hamburger menu, particularly when viewing on mobile

As a newcomer to web development, I decided to challenge myself by building an E-Commerce website to enhance my skills. To ensure mobile responsiveness, I opted for a hamburger menu to hide the navbar content. However, despite resizing working flawlessly, ...

Guide to select all the checkboxes within rows using AngularJS

New to AngularJs, I am facing a challenge with the code below. The table is populated using Angularjs and includes a selectAll checkbox in the header that should select all checkboxes in the table when checked. However, due to sorting and filtering capabil ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

What sets apart the meteor angular:angular and urigo:angular-meteor packages from each other?

I am currently working on developing an app that incorporates both meteor and angular. There are two main angular packages that I have come across: one is called angular:angular, and the other is named urigo:angular-meteor According to the angular:angula ...

Set the style of the mat-select element

I'm having an issue with my select option in Angular Material. The options look fine, but when I select one, the strong tag disappears. Can anyone help me style only that part? Thank you in advance. <mat-select formControlName="projectId" ...

Leveraging ng-hide in Angular to show or hide elements based on the state

Is there a way to utilize the ng-hide directive based on the value selected in a dropdown menu? Specifically, I am looking to display #additional-option if option C is chosen from the dropdown list. <div class="form-group"> <label class="co ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Transform Gulp task into webpack configuration

Main responsibilities: Concatenate and minify JS files in a specific order Ensure that minification does not disrupt AngularJS modules Include an MD5 string in the output JS filename to prevent browser caching, e.g. bundle-24141asd.js Update the generate ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

Updating the output without the need for a page refresh following the insertion of data into the database

I'm interested in enhancing the interactivity of this section in my code. Currently, I utilize a form to send announcements via ajax to a php file which successfully updates my database. The table displays the data effectively. However, I want these c ...

Can ReactJS and jQuery be used together or are they mutually exclusive?

As a beginner in the world of ReactJS, I am intrigued by how this library essentially handles all DOM node rendering without any need for interference from other libraries like jQuery. However, this does pose a challenge as many convenient jQuery plugins ...

Incorporate measurement markers into the graphic (ESRI JavaScript)

Is there a way to add a scale to a single graphic in a graphics layer? I currently have all the graphics shown in the same scale, but I need each graphic to have a different scale. I added the graphics using map.graphics.add() and SimpleSymbol. Any sugge ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

Using Vue.js to dynamically append varying inputs upon user interaction

When I select an option, I want to display different types of inputs based on the selected option. For Example: Select input -> show input fields Select textarea -> show text areas Select boolean -> show radio buttons The Code This is where I choose ...