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

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

问题描述

下面的脚本显示使用纳克重复店车。对于数组中的每一个元素,它会显示的项目名称,数量和分类汇总( product.price * product.quantity )。

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

什么是重复计算元素的总价simpliest方式?

What is the simpliest 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重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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