Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 
like image 675
keepthepeach Avatar asked Mar 29 '14 12:03

keepthepeach


People also ask

What is Ng-repeat in AngularJS?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

How do I use track in NG-repeat?

To avoid this problem, you can use "track by" with ng-repeat. In track by you have to use angular expression that will be used to uniquely identify the each items in collection or model. "track by" tells the angular js that how angular js will track the association between DOM and the model (i.e. collection).

Why we use NG-repeat in Angular?

Example# ng-repeat is a built in directive in Angular which lets you iterate an array or an object and gives you the ability to repeat an element once for each item in the collection. To repeat multiple DOM elements by defining a start and an end point you can use the ng-repeat-start and ng-repeat-end directives.


1 Answers

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; } 
like image 52
Vamsi Avatar answered Sep 19 '22 16:09

Vamsi