在值更改时计算ng-repeat中的和

时间:2017-05-29 07:40:06

标签: angularjs sum angularjs-ng-repeat

当值更改时,我想计算总和

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

查看

function getparamNameMultiValues(paramName){
	    var sURL = window.document.URL.toString();
	    var value =[];
	    if (sURL.indexOf("?") > 0){
	        var arrParams = sURL.split("?");
	        var arrURLParams = arrParams[1].split("&");
	        for (var i = 0; i<arrURLParams.length; i++){
	            var sParam =  arrURLParams[i].split("=");
	            console.log(sParam);
	            if(sParam){
		            if(sParam[0] == paramName){
		            	if(sParam.length>0){
		            		value.push(sParam[1].trim());
		            	}
		            }
	            }
	        }
	    }
	    return value.toString();
	}

想要在加载时计算复合材料

3 个答案:

答案 0 :(得分:1)

您的观点:

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

控制器:

$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;
}

当您使用ngModel指令或使用插值时,您的数据是双向绑定的,每次更改模型时都会重新计算函数值。

答案 1 :(得分:1)

像这样改变你的观点

<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>

答案 2 :(得分:1)

试试这个:

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