Search code examples
angularjsangularjs-ng-repeat

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

Solution

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