在 ng-repeat 中更新总计
Update Totals in ng-repeat
请看这个fiddle
我想要做的是 calculate/update 嵌套 ng-repeat 中每一列的总计:
<tr ng-repeat="cust in customers">
<td>{{cust.name}}</td>
<td ng-repeat="book in books">
<p ng-init="index=getIndex(book.id, cust.id)"></p>
<input ng-model="qtys[index].qty">
</td>
</tr>
<tr>
<td>Total</td>
<td ng-repeat="book in books">
<input type=text value="{{sumQty(book.id)}}">
</td>
</tr>
我有 2 个问题需要解决:
输入框现在显示我数组中的正确值。我正在尝试使用 ng-init 首先根据我传入的 custId 和 bookId 从数组中获取索引:
<p ng-init="index=getIndex(book.id, cust.id)"</p>
<input ng-model="qtys[index].qty">
我想我不确定如何正确绑定 ng-model
- 总计无效。但我想我需要先解决第一个问题才能让它工作。
请帮忙。谢谢
你几乎答对了。问题出在您的 getIndex 方法中 - 您在那里执行的 return 不是来自 getIndex 的 return,它只是退出您传递给 forEach 的函数。这样修改就可以了
$scope.getIndex = function(bookId, custId) {
var index = null;
angular.forEach($scope.qtys , function(item, idx) {
if (item.bookId == bookId && item.custId == custId) {
index = idx;
};
});
return index;
};
scope.sumQty 似乎还没有完成(它需要一个列表作为参数,但你正在向它传递一个 id)。修复它的一种方法是让它接受 id
$scope.sumQty = function(id) {
var total=0;
angular.forEach($scope.qtys , function(item){
if(item.bookId == id) {
total+= parseInt(item.qty);
}
});
return total;
}
请看这个fiddle
我想要做的是 calculate/update 嵌套 ng-repeat 中每一列的总计:
<tr ng-repeat="cust in customers">
<td>{{cust.name}}</td>
<td ng-repeat="book in books">
<p ng-init="index=getIndex(book.id, cust.id)"></p>
<input ng-model="qtys[index].qty">
</td>
</tr>
<tr>
<td>Total</td>
<td ng-repeat="book in books">
<input type=text value="{{sumQty(book.id)}}">
</td>
</tr>
我有 2 个问题需要解决:
输入框现在显示我数组中的正确值。我正在尝试使用 ng-init 首先根据我传入的 custId 和 bookId 从数组中获取索引:
<p ng-init="index=getIndex(book.id, cust.id)"</p> <input ng-model="qtys[index].qty">
我想我不确定如何正确绑定 ng-model
- 总计无效。但我想我需要先解决第一个问题才能让它工作。
请帮忙。谢谢
你几乎答对了。问题出在您的 getIndex 方法中 - 您在那里执行的 return 不是来自 getIndex 的 return,它只是退出您传递给 forEach 的函数。这样修改就可以了
$scope.getIndex = function(bookId, custId) {
var index = null;
angular.forEach($scope.qtys , function(item, idx) {
if (item.bookId == bookId && item.custId == custId) {
index = idx;
};
});
return index;
};
scope.sumQty 似乎还没有完成(它需要一个列表作为参数,但你正在向它传递一个 id)。修复它的一种方法是让它接受 id
$scope.sumQty = function(id) {
var total=0;
angular.forEach($scope.qtys , function(item){
if(item.bookId == id) {
total+= parseInt(item.qty);
}
});
return total;
}