Calcuate Sum in ng-repeat when Value Change

故事扮演 提交于 2020-01-05 04:00:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!