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>
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.
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).
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With