JLT JLT - 2 years ago 835
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 ?



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

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



Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download