Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat - count within html loop

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?

like image 606
Alias Avatar asked Sep 04 '14 13:09

Alias


People also ask

What is Ng-repeat in HTML?

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 you pass an index in NG-repeat?

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.

Why is NG-repeat not working?

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.

What is $Index in AngularJS?

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>


2 Answers

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

like image 36
V31 Avatar answered Sep 21 '22 03:09

V31


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>
like image 191
Prasad K - Google Avatar answered Sep 18 '22 03:09

Prasad K - Google