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>
This is my solution
sweet and simple custom filter:
(but only related to simple sum of values, not sum product, I've made up
sumProduct
filter and appended it as edit to this post).JS Fiddle
EDIT: sumProduct
This is
sumProduct
filter, it accepts any number of arguments. As a argument it accepts name of the property from input data, and it can handle nested property (nesting marked by dot:property.nested
);here's JS Fiddle and the code
JS Fiddle
Another way of solving this, extending from Vaclav's answer to solve this particular calculation — i.e. a calculation on each row.
To do this with a calculation, just add a calculation function to your scope, e.g.
You would use
{{ datas|total:calcItemTotal|currency }}
in your HTML code. This has the advantage of not being called for every digest, because it uses filters, and can be used for simple or complex totals.JSFiddle
You can calculate total inside
ng-repeat
follow:Check result here: http://plnkr.co/edit/Gb8XiCf2RWiozFI3xWzp?p=preview
In case automatic update result: http://plnkr.co/edit/QSxYbgjDjkuSH2s5JBPf?p=preview (Thanks – VicJordan)
I prefer elegant solutions
In Template
In Controller
If you're using ES2015 (aka ES6)
This is also working both the filter and normal list. The first thing to create a new filter for the sum of all values from the list, and also given solution for a sum of the total quantity. In details code check it fiddler link.
check this Fiddle Link
This is a simple way to do this with ng-repeat and ng-init to aggregate all the values and extend the model with a item.total property.
The ngInit directive calls the set total function for each item. The setTotals function in the controller calculates each item total. It also uses the invoiceCount and invoiceTotal scope variables to aggregate (sum) the quantity and total for all items.
for more information and demo look at this link:
http://www.ozkary.com/2015/06/angularjs-calculate-totals-using.html