Calculating sum of repeated elements in AngularJS ng-repeat

keepthepeach picture keepthepeach · Mar 29, 2014 · Viewed 239.8k times · Source

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>

Answer

Vamsi picture Vamsi · Mar 29, 2014

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