Use ng-repeat to dynamically calculate the sum of values in a textbox in AngularJS

Greetings everyone! I am currently utilizing AngularJS and I am attempting to sum the values that are entered in an ng-repeat text box, row by row. However, my current solution sums up all the data instead of doing it row by row. Can anyone offer guidance on how to resolve this issue?

I have included a link to my fiddle here: https://jsfiddle.net/rjj/zm9941tm/1/

Answer №1

<td><input type="text" ng-model="x.result = +x.value1 + +x.value2;"></td>

To resolve the issue, simply set the result as the sum of value1 and value2 with a plus sign added to convert strings to numbers for easy calculation. Check out this example on Fiddle: https://jsfiddle.net/zm9941tm/4/

Answer №2

To easily achieve this, simply utilize the following code snippet:

ng-model="x.result = x.value1 + x.value2"

For a practical demonstration, refer to this fiddle

https://jsfiddle.net/kL315y2h/1/

Answer №3

If you are working with an array named "myArray" in ng-repeat, one way to calculate the sum is by creating a function in the controller as follows:

$scope.calculateTotal = function calculateTotal(array) {

  var sum = 0;
  array.forEach(function (value) {
    this.sum += value;
  }, this); 

  return sum;
}

Then, after the ng-repeat table, you can display the total sum by adding another element containing {{calculateTotal(myArray}}

Answer №4

Experimented with fixed values to assist you in understanding...

var app = angular.module('plunker', []);


app.controller('EditorController', function($scope) {
$scope.records = [
    {
      "value1" : 10,
      "value2" : 20,
"result" :0
    },
    {
       "value1" : 30,
      "value2" : 40,
"result" :0
    },
    {
      "value1" : 50,
      "value2" : 60,
"result" :0
    },
    {
      "value1" : 70,
      "value2" : 80,
"result" :0
    }
  ]
  $scope.func=function(x){
    return x.value1+x.value2;
  }
});
<!doctype html>
<html ng-app="plunker" >
<head>
 
  
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div ng-controller="EditorController">
      <table  border="1">

<tr>
<th>A</th>
<th>B</th>
<th>Result</th>
</tr>
<tr ng-repeat="x in records">
  <td><input type="text" ng-model="x.value1"></td>
    <td><input type="text" ng-model="x.value2"></td>
  <td><input type="text"  ng-init="result = func(x);" ng-model="result"></td>
 
</tr>
</table>
  </div>
</body>
</html>

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

Tips for simulating difficult private attributes within a class during unit testing in TypeScript

Is there a way to mock the value of a hard private property in a unit test? For example, how can I expect something like expect(event.getEventHis()).toBeEqual(['a', 'b']) export class EventController { #event: []; constructor() { ...

"Trouble with Heroku: JavaScript script failing to load with 404

My adventure in building my first web app using MEAN on Heroku has been both thrilling and frustrating. I meticulously followed their guide to set up a sample app, downloaded the code, and made modifications to have a customized login page. However, I hit ...

"Using AngularJS to display a blank option as preselected in an ng-option

Having an issue with displaying a preselected value as the selected option in my select element. Check out the code below: <select ng-model="data.company" ng-options="company as company.name for company in companies"></select> $scope.compani ...

What is the best way to activate a function from a modal component without having the function embedded in Angular 14?

I've recently been putting together an e-commerce application using Angular 14. Currently, I'm tackling a form that must only be submitted once the user accepts the "Terms & Conditions" shown in a modal popup. The FormComponent and ModalCompone ...

The attempt to install myapp using npx create-react-app has failed. The installation has been aborted

Attempting to create a new project using npx create-react-app my-app resulted in an error message saying Aborting installation. Initially, I had node v14.17.1 installed. Upgrading to the latest version 16.4.0 did not resolve the issue. Even running sudo ...

My goal is to design a dynamic textbox for a website that allows users to customize the text in any format they desire

I want to create a versatile textbox on my website that allows users to change the text format as they desire. Unfortunately, I am facing some issues with implementing this feature. Here is the code I have developed so far. <body> <h1>< ...

What is the purpose of adding "/dist" to the library import statement?

Currently, I am in the process of developing a react component library using vite as my primary build tool. After successfully compiling the project and deploying it to the npm registry, I encountered an issue when importing it into my client app. Specifi ...

What steps should I take to create a functional image scrolling effect similar to the one shown in this example?

Recently, I came across and was intrigued by the "image slide effect" featured on their homepage. The way the background image changes as you scroll up, leading you through different introductory slides before reaching the main content of the site caught ...

Stripping CSS from my HTML using TinyMCE

I have created a custom Javascript function that retrieves the content of an HTML file from my server and then integrates it into a TinyMCE editor. Here is the function: function LoadTemplate(url) { $.post(url, function (data) { // Access the ...

Best method for creating HTML elements with jQuery

I've come across various styles and methods for creating elements in jQuery, each with its own unique approach. I am interested in discovering the most effective way to construct elements and whether a specific method stands out as superior for any pa ...

Assigning the href attribute dynamically

How can you dynamically set the href attribute of the <a> tag using jQuery? In addition, what is the method for retrieving the value of the href attribute from the <a> tag with jQuery? ...

I seem to be facing some difficulty in dynamically calling my buttons in AngularJS

Can you assist me in solving this problem? I am new to Angular and just starting out. Initially, there is only one button on load called "Add list". When the user clicks on this button, they are able to add multiple lists. Each list contains a button labe ...

Transferring Data Between Two Forms

Is there a way to transfer data between two HTML forms? For example, let's say we have two forms: Form 1: Contains a field for name and a submit button. Form 2: Contains fields for name, email, and a submit button. I would like to be able to fill o ...

Attaching identical class and event handlers to numerous dynamically created elements

I am facing a challenge with the following HTML structure: <a href="#" @click.prevent="toggleClass">Show/Hide</a><br> <li :class="{myClass: showItems}">Item 1</li> <a href="#" @click.prevent="toggleClass">Show/Hide< ...

Sending information from Vue to Express for processing

Is there a way to pass data from Vue to an express server? For example, in the scenario below, I am looking to send the data logged in my Vue function to the "id" variable on the server side. expressApp.post('/delete' , function (request, respons ...

Customize your Shopify Messenger icon using JavaScript!

Shopify recently introduced a new feature that allows customers to contact store owners through messenger. My client has requested me to customize the appearance of this icon with their branded icon instead. https://i.stack.imgur.com/uytpd.png I have not ...

The menu is loaded dynamically by Ajax from JavaScript once the page is refreshed

$('#subregionListPage').bind('pageinit', function(event){ var output = $('#subregions'); var region = getUrlVars()["reg"]; $.ajax({ url: 'http://localhost:8888/my/getsubregions.php', dat ...

Execution priority of Javascript and PHP in various browsers

I implemented a basic JavaScript function to prevent users from using special characters in the login form on my website: $("#login_button").click(function(){ formChecker(); }); function formChecker() { var checkLogin = docum ...

Vue.js does not seem to be properly assigning attributes that are declared within the data object array

Trying to get a hang of vue.js and looking to create dynamic product cards using it: This is the snippet from my HTML file: <div id="app"> <card v-for="products in product" :productname="product.productname"></card> </div> Here&a ...

Struggling to remove the image tag from the jQuery ajax response

My web app is designed to send an ajax post request to a PHP script, which then returns a chunk of HTML data. This HTML includes an image and a table of information. The challenge I'm facing is how to extract the image from the rest of the HTML so tha ...