Is there anyway to count an item, then display it outside of the loop?
<tr ng-repeat="value in values">
<td>value.total</td>
</tr>
<tr>
<td>Total Of All Values: {{ total }}</td>
</tr>
I've tried using ng-init()
to no success as I think it's over-riding each time.
<tr ng-repeat="value in values">
<td ng-init="total = total + value.total>value.total</td>
</tr>
<tr>
<td>Total Of All Values: {{ total }}</td>
</tr>
Is there anyway of doing it here, without making a function in my controller?
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.
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index variable in that scope. So what you need to do is reach up to the parent scope, and use that $index . Save this answer.
Solution 1. There are two mistakes in your code: In your table, you have to wrap the properties between {{ and }}, for example {{employee. Fname}} instead of just employee.
Stay on the bleeding edge of your favorite technologies. $index is a way to show which iteration of a loop you're in. If we set up an ng-repeat to repeat over the letters in 'somewords', like so: <div ng-app="app"> <div ng-repeat="item in 'somewords'.split('')"> {{$index + 1}}. {{item}} </div> </div>
You can make use of $parent notation to access a $scope variable (from outside ng-repeat) in the ng-repeat scope. So now after initializing it will calculate the total and store it in the $scope variable which was initialized outside.
Code:
<div ng-app ng-controller="test">
<table ng-init="total=0;">
<tr ng-repeat="value in values">
<td ng-init="$parent.total = total + value">{{value}}</td>
</tr>
<tr>
<td>Total Of All Values: {{ total }}</td>
</tr>
</table>
</div>
Working Fiddle
total
which is initialized in ng-repeat will be of a different scope and can not be accessed outside the loop.
Try this:
<table ng-init="total = 0">
<tr ng-repeat="value in values">
<td ng-init="$parent.total = $parent.total + value.total">{{value.total}}</td>
</tr>
<tr>
<td>Total Of All Values: {{ total }}</td>
</tr>
</table>
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