我有一个 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 的“collections”将是一个包含 6 个对象的数组,我使用 GET 方法从 API 获取这些对象并将数据存储在 $scope 中。
带有 ng-model 的“Total”行来自后端,微积分已经完成,但我需要一种方法在客户端动态更新时将其显示。
我尝试过 $watch 和 $watchCollection 以及 ng-change 但我找不到让它工作的方法。在我的 Controller 中,我使用 for 来遍历对象数组并尝试对每个 [i] 位置求和,但这不起作用。
我的问题还有其他解决方案吗?
这是我在 Controller 中尝试的内容:
$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>
内的值的,因此 Angular 模板 ( {{X}}
) 和 ng-model 正在竞争 <td></td>
内的显示值在你给出的代码中
关于javascript - Angular.Js 使用其他 3 个输入的总和动态更新输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38837680/