1

I followed the following tutorial for adding two values in Angular; Addition of Two Numbers in AngularJS

But now I have to sum dynamic text box values inside ng-repeat.

I have the following Code

HTML Code

 ......
        <table>
            <tr>
                <th>Name</th>
                <th>Days</th>
            </tr>
            <tr ng-repeat="si in serImp">
                <td>{{si.Name}}</td>
                <td><input type="number" ng-model="si.Days" /></td>
            </tr>
        </table>
        .......
        <button ng-click="sum()">Calculate</button>
        .......

JS code

.........
        $scope.serImp = [];
        $scope.serImp = data;
                // here data is object contain multiple Name+Durations e.g. 
        /*data = 
        [0]
   Name:"first"
   Days: 1
[1]
   Name:"second"
   Days: 2
[2]
   Name:"third"
   Days: 3*/

         $scope.sum = function () {
// sum code goes here
    }
    ........

My Question is : How can I get the sum of the values/numbers from the ng-model="si.Days"

2 Answers 2

1

Use reduce to sum up all the days. When you modify the values with ng-model you're manipulating the $scope.serImp array. You can then use these values to calculate the sum.

$scope.sum = function () {
     return $scope.serImp.reduce(function(prv, cur) { 
         return prv.Days + cur.Days; 
     });
}

Reduce takes an array and reduces it to one value by applying one function to all of its elements. In our case just simply adding up all the days.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Sign up to request clarification or add additional context in comments.

Comments

1

I will create function that will return all Days total & will directly bind to html

{{totalDays()}}

Code

$scope.totalDays = function(){
  var totalDays = 0;
  angular.forEach( $scope.serImp, function(si){
     if(si.Days && !isNaN(si.Days)){
        totalDays += Number(si.Days);
     }
  })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.