Mohammad Fareed
Mohammad Fareed

Reputation: 1972

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

Upvotes: 1

Views: 950

Answers (3)

Jenny
Jenny

Reputation: 663

try this :

<td class="composite">{{act.subjects | map:'score' | sum}}</td>

Upvotes: 1

Ramin Farajpour
Ramin Farajpour

Reputation: 417

change your view like this

<tr ng-repeat="act in ctrl.otsact.tests" ng-init="act.subjects.total=0" 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" 
ng-init="act.subjects.total=act.subjects.total+sub.score" aria-label="Score">
    </md-input-container>
</td>
<td class="composite">
    {{act.subjects.total}}
</td>
<td><span ng-click="ctrl.removeOTSACT(act.id)"> x </span></td>
</tr>

Upvotes: 1

btlm
btlm

Reputation: 350

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.

Upvotes: 1

Related Questions