Alias
Alias

Reputation: 3081

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?

Upvotes: 6

Views: 6361

Answers (4)

Prasad K - Google
Prasad K - Google

Reputation: 2584

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>

Upvotes: 6

Nikolas
Nikolas

Reputation: 1176

Although they do seem to be similar ngRepeat does not work like a for loop in an imperative programming language. The ngRepeat directive consists of two steps that run seperately. First, it produces an array / a map with the repeatet values. Secondly, it renders the template (the elements inside the element with ngRepeat) for each repeatet value. It does not however iterate over a code block like an imperative programming language.

Even though you may achieve what you try to do with $parent.total, you may run into other pitfalls with this solution as soon as the contents of your array change. To cut it short, you should rather find another way to sum up the values in the array.

In my opinion, the best place to sum up the values is the controller with a line like this:

$scope.total = values.reduce(function (a,b) {return a+b});

Upvotes: 1

Entomo
Entomo

Reputation: 275

You could always do this in your JS function.

        $scope.values = data;
        angular.forEach($scope.values,function(value){
          $scope.total += value.value;
        });

Working plunker: http://plnkr.co/edit/5WZ9alCXzq115wi3xl4B?p=preview

Upvotes: 0

V31
V31

Reputation: 7666

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

Upvotes: 3

Related Questions