JLT JLT - 6 months ago 306
AngularJS Question

Calculating sum of repeated elements in AngularJS ng-repeat

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
).

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>


Thanks.

Answer

In Template

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

In Controller

$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;
}
Comments