Search code examples
angularjssumangularjs-ng-repeat

Calculate Sum in ng-repeat when Value Change


When Value Changes I want to Calculate the Sum

<tr ng-repeat="act in ctrl.otsact.tests" ng-if="ctrl.editToggle">
    <td>
        <md-input-container>
            <input type="text" ng-model="act.test_date" class="dateField" aria-label="Test Date">
        </md-input-container>
    </td>
    <td ng-repeat="sub in act.subjects" >
        <md-input-container>
            <input type="number" ng-model="sub.score" aria-label="Score">
        </md-input-container>
    </td>
    <td class="composite">
        100
    </td>
    <td><span ng-click="ctrl.removeOTSACT(act.id)"> x </span></td>
</tr>

View

Date of Test    English Math    Reading Science Writing Composite
2017-05-29      13      13      13      13      13      65
2017-05-29      2       2       2       2       2       10

Want to calculate the Composite when Loading


Solution

  • Your view:

    <td class="composite">{{ getSum(act) }}</td>
    

    Controller:

    $scope.getSum = function(act){
        var sum = 0;
        for(var i = 0; i < act.subjects.length; ++i){
            var subject = act.subjects[i];
            sum += subject.score;
        }
        return sum;
    }
    

    As you are using ngModel directive or using interpolation, your data is two-way-bound and function value will be recalculated every time you change your model.