我有一个包含6行4列的表(第四列是合计:应为以上3列的总和)。基本上我想做的是计算每一列的总和并在第四列中显示总数。我的表是使用ng-repeat生成的。
就像是:
<table>
<thead>
<tr>
<th ng-repeat="item in items">{{item}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>Input1:</td>
<td ng-repeat="collection in collections">
<input type="text" ng-model="collection.row1">
</td>
</tr>
<tr>
<td>Input2:</td>
<td ng-repeat="collection in collections">
<input type="text" ng-model="collection.row2">
</td>
</tr>
<tr>
<td>Input3:</td>
<td ng-repeat="collection in collections">
<input type="text" ng-model="collection.row3">
</td>
</tr>
<tr>
<td>Sum:</td>
<td ng-repeat="collection in collections" ng-model="collection.total">
{{collection.total}}
</td>
</tr>
</tbody>
</table>
来自ng-repeat的“集合”将是一个包含6个对象的数组,这些对象是我使用GET方法从API获取并将数据存储在$ scope中的。
带有ng-model的“总计”行来自已经进行了演算的后端,但是我需要一种在客户端上显示它的方法,因为它正在动态更新。
我试过$ watch和$ watchCollection以及ng-change,但是我找不到使它工作的方法。在控制器中,我使用了for来遍历对象数组,并尝试对每个[i]位置求和,但这没有用。
我的问题还有其他解决方案吗?
这是我在控制器中尝试过的方法:
$scope.collections = [];
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.collections[i].length; i++){
var myItems= $scope.collections[i];
total = (myItems.row1+ myItems.row2+ myItems.row3);
}
return total;
};
谢谢你。
为什么不简单地在模板中这样做呢?
<td>{{collection.row1 + collection.row2 + collection.row3}}</td>
另外,除非是,否则不应存在ng-model <input>
。那可能就是您的主要错误所在。Ng-model会尝试在的内设置值<td>
,因此,角度模板({{X}}
)和ng-model会<td></td>
在给定代码中竞争内的显示值
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句