Updating a table cell triggers a change in every cell

I have a table with columns and I need to calculate values in other cells when there is a change event on the table. I want to use ng-change so that the changes are seen immediately. However, I am unsure of how to properly utilize ng-model - if it is used in one row, it affects all rows, causing each row to be recalculated, which is not the intended outcome. I only want to update one row at a time.

Angular requires ng-model when using ng-change. How can I correctly implement ng-change with multiple rows in a table?

I know I can achieve this using jQuery's onchange event, but since I already have a controller in HTML, I would prefer to handle everything in Angular.

Here is an example of one of the rows:

<tr class="jtable-data-row jtable-row-even" 
data-record-key="110000001"><td>110000001</td>
            <td><input type="text" 
    ng-change="RecalculateValues($event);" ng-model="Quantity" value="1"></td>
            <td><input type="text"
    ng-change="RecalculateValues($event);" ng-model="Bruto" value="7.15"></td>
            <td><input type="text"
    ng-change="RecalculateValues($event);" ng-model="Neto" class="cellContent" class="cellContent" value="17"></td>
            </tr>

EDIT:

Plunker here demonstrates my issue - even though the ng-change event is connected to the input values, the cells are not updating as expected.

Answer №1

Your approach needs some adjustment.

For instance:

<tr>
  <td>{{total}}</td>
  <td>
    <input type="text" ng-change="calculate()" ng-model="quantity">
  </td>
  <td>
    <input type="text" ng-change="calculate()" ng-model="bruto">
  </td>
</tr>

In the Controller:

$scope.quantity = 1;
$scope.bruto = 7.5;
$scope.total = 0;

$scope.calculate = function() {
  $scope.total = $scope.quantity * $scope.bruto;
}

$scope.calculate();

If there are multiple table rows, you will need an array of objects, each with a quantity, bruto, and total.

<tr ng-repeat="n in valuesArray">
  <td>{{n.total}}</td>
  <td>
    <input type="text" ng-change="calculate($index)" ng-model="n.quantity">
  </td>
  <td>
    <input type="text" ng-change="calculate($index)" ng-model="n.bruto">
  </td>
</tr>

In the Controller:

$scope.valuesArray = [
  {quantity: 1, bruto: 7.5, total: 0},
  {quantity: 1, bruto: 7.5, total: 0},
  {quantity: 1, bruto: 7.5, total: 0},
];

$scope.calculate = function(index) {
  $scope.valuesArray[index].total = $scope.valuesArray[index].quantity * $scope.valuesArray[index].bruto;
}

Answer №2

The absence of app initialization is causing the method on change to not be triggered.

To resolve this, make sure to include <body ng-app="myApp">

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

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Using JSON to pass a function with parameters

I have a small issue that I'm struggling to solve. My dilemma lies in sending a JSON with a function, along with parameters. Typically, it's easy to send a function in JSON like this: var jsonVariable = { var1 : 'value1', var2 : &apos ...

Creating a flexible image layout within a container with relative positioning

I attempted to create a basic slideshow with images sliding from right to left as an animation: let slides = document.querySelectorAll('.img-container'); let l = slides.length; let i = 0; setInterval(function(){ i = (i + 1) % l; if(i == 0){ f ...

Troubleshooting problems with the CSS code for a progress bar in Gmail

I recently came across a unique progress bar design on Gmail and wanted to implement something similar. I found some code snippets on this webpage: . However, I encountered an issue where the progress bar was only displaying in Internet Explorer but not in ...

Tips for adding additional rows or cells to a table with jQuery

Similar Questions: How to Add Table Rows with jQuery Adding Rows Dynamically using jQuery. I am currently working with a table that contains one row and five editable cells for user input. My goal is to implement an "Add Row" feature using jQuery ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

Using interpolation brackets in Angular2 for variables instead of dots

I'm curious if Angular2 has a feature similar to the bracket notation in Javascript that allows you to use variables to select an object property, or if there is another method to achieve the same functionality. Here is the code snippet for reference ...

Unable to extract query parameters from URL using Express JS as req.query returns an empty object

I came across discussions about this issue here and here, but unfortunately, the solutions provided didn't work for me. I'm attempting to extract parameters from the URL using req.query. In my server.js file, I've implemented the following: ...

The Google map shifts beyond the perceived limits of the world

Is anyone else encountering an issue with Google Maps where you can now pan beyond the poles? It used to stop at the poles before, correct? The website I'm currently working on runs a location-based query on our server every time a user pans or zooms ...

Storing data efficiently with Angular 2's local storage service

I am attempting to create a ToDoList using localstorage within a service. add.component.ts export class AddComponent implements OnInit { item: Item[]; constructor( private router: Router, private itemService: ItemService) { } ...

Discover the best practices for utilizing the npm commands.test function

Looking to create a function that can return the output from running npm test. (this function can be called as npm.commands.test(packages, callback) here) Attempted to use it in this way: var npm = require("npm"); npm.load('', function(err, np ...

Obtain the filepath of the uploaded file

After working on a code to allow users to upload images to the server, I encountered an issue. Here is my setup: The backend of my system is built using Node JS. My main goal is to retrieve the file path of the uploaded image so that I can successfully up ...

"Enhance User Interactions with Angular-ui Tooltips Featuring

I recently integrated bootstrap tooltips into my application. While the "normal" tooltips are working fine, I encountered an issue with tooltip-html-unsafe. It seems to display an empty tooltip. Here is my tooltip code: <a><span tooltip-placeme ...

React error: Objects cannot be used as children in React components

Upon trying to display data using REACT, an error message stating "Objects are not valid as a React child. If you meant to render a collection of children, use an array instead" is encountered. The issue arises when fetching records from a MongoDB collect ...

The absence of responseJSON in the jquery ajax response is causing an issue

Currently, I am developing a small web framework for conducting an HCI study and have encountered the following issue: In my setup, I have a Node server running with Express to serve local host data from JSON files. While it may not be the most advanced d ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Modify the website address and show the dynamic content using AJAX

$(function(){ $("a[rel='tab']").click(function(e){ //capture the URL of the link clicked pageurl = $(this).attr('href'); $("#Content").fadeOut(800); setTimeout(function(){ $.ajax({url:pageurl+'?rel=tab&apo ...

Customized settings saved in local storage using JavaScript

Here is the script I am currently using for my app: <script> if (localStorage.getItem("0") === null) { //do nothing } else if(localStorage.getItem("1")===null{ } else if(localStorage.getItem("2")===null{ } else if(localStorage.getItem("3")===null ...

What is the best way to divide data prior to uploading it?

I am currently working on updating a function that sends data to a server, and I need to modify it so that it can upload the data in chunks. The original implementation of the function is as follows: private async updateDatasource(variableName: strin ...

Avoiding the backslash in JavaScript

<script type="text/javascript"> console.log(#Fileurl#); jQuery.ajax({ url: "http://xyz:8800/aaa/bbb/ccc", type:'POST', dataType: 'JSON', data:{"file":"#Fileurl#"}, success: function ...