问题
When Value Changes i want to Calcualte 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 calcluate the Composite when Loading
回答1:
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.
回答2:
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>
回答3:
try this :
<td class="composite">{{act.subjects | map:'score' | sum}}</td>
来源:https://stackoverflow.com/questions/44237038/calcuate-sum-in-ng-repeat-when-value-change