jose
jose

Reputation: 1054

ng-repeat sum values in textbox dynamically in angualrjs

hi all I am using angular js i am trying to do sum the values were placed in a ng-repeat text box based row I tried it's sum the whole data anyone can help how to solve the issue

here I attached my fiddle:https://jsfiddle.net/rjj/zm9941tm/1/

Upvotes: 0

Views: 468

Answers (4)

Sa E Chowdary
Sa E Chowdary

Reputation: 2075

Tried some thing with static values ...hope this may helps you

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>

Upvotes: 0

stzoannos
stzoannos

Reputation: 938

Assuming that the array that you are using in ng-repeat is "myArray", you could add a function in the controller like:

$scope.calculateSum = function calculateSum(array) {

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

  return sum;
}

and after the ng-repeat table, you add another element with value {{calculateSum(myArray}}

Upvotes: 0

Bunyamin Coskuner
Bunyamin Coskuner

Reputation: 8859

You can just use

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

Check this fiddle

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

Upvotes: 0

gauravmuk
gauravmuk

Reputation: 1616

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

This would fix the issue. Set the result as a sum of value1 and value2 and +has been added to change string to numbers for easy sum. Fiddle: https://jsfiddle.net/zm9941tm/4/

Upvotes: 2

Related Questions