计算AngularJS ng-repeat中重复元素的总和 [英] Calculating sum of repeated elements in AngularJS ng-repeat

查看:30
本文介绍了计算AngularJS ng-repeat中重复元素的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的脚本使用 ng-repeat 显示购物车.对于数组中的每个元素,它显示项目名称、数量和小计 (product.price * product.quantity).

The script below displays a shop cart using ng-repeat. For each element in the array, it shows the item name, its amount and the subtotal (product.price * product.quantity).

计算重复元素总价的最简单方法是什么?

What is the simplest way for calculating the total price of repeated elements?

<table>

    <tr>
        <th>Product</th>
        <th>Quantity</th>
        <th>Price</th>
    </tr>

    <tr ng-repeat="product in cart.products">
        <td>{{product.name}}</td>
        <td>{{product.quantity}}</td>
        <td>{{product.price * product.quantity}} €</td>
    </tr>

    <tr>
        <td></td>
        <td>Total :</td>
        <td></td> <!-- Here is the total value of my cart -->
    </tr>

</table>

推荐答案

在模板中

<td>Total: {{ getTotal() }}</td>

在控制器中

$scope.getTotal = function(){
    var total = 0;
    for(var i = 0; i < $scope.cart.products.length; i++){
        var product = $scope.cart.products[i];
        total += (product.price * product.quantity);
    }
    return total;
}

这篇关于计算AngularJS ng-repeat中重复元素的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆