Angularjs 内包含计算表达式的列的总和
Sum total of a column with a calculated expression inside Angularjs
这是我的代码 angularjs:
<table ng-controller="SimulateController">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td><input ng-model="item.quantity" /></td>
<td>{{item.price}}</td>
<td>{{item.quantity * item.price}}</td>
</tr>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
我需要这样的东西来获得总价列的总和:
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th>totalsum{{item.quantity * item.price}}</th>
</tr>
</tfoot>
我如何得到这个?尽管寻找了其他主题,但我找不到与计算表达式相关的任何内容,谢谢。
在您的控制器中,定义一个计算总数的函数getTotal(items)
;
$scope.getTotal = function (items) {
// compute and return the total price
}
然后在模板中:
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th>{{getTotal(items)}}</th> <!-- or {{getTotal(items) | currency}} -->
</tr>
</tfoot>
计算总数的函数可以实现如下:
$scope.getTotal = function (items) {
var total = 0;
angular.forEach(items, function (item) {
if (item.quantity) {
total += item.quantity * item.price;
}
};
return total;
}
理想情况下,您可以使用 reduce
来做到这一点,但这是题外话。
这是我的代码 angularjs:
<table ng-controller="SimulateController">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
</thead>
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td><input ng-model="item.quantity" /></td>
<td>{{item.price}}</td>
<td>{{item.quantity * item.price}}</td>
</tr>
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
我需要这样的东西来获得总价列的总和:
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th>totalsum{{item.quantity * item.price}}</th>
</tr>
</tfoot>
我如何得到这个?尽管寻找了其他主题,但我找不到与计算表达式相关的任何内容,谢谢。
在您的控制器中,定义一个计算总数的函数getTotal(items)
;
$scope.getTotal = function (items) {
// compute and return the total price
}
然后在模板中:
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th>{{getTotal(items)}}</th> <!-- or {{getTotal(items) | currency}} -->
</tr>
</tfoot>
计算总数的函数可以实现如下:
$scope.getTotal = function (items) {
var total = 0;
angular.forEach(items, function (item) {
if (item.quantity) {
total += item.quantity * item.price;
}
};
return total;
}
理想情况下,您可以使用 reduce
来做到这一点,但这是题外话。