tdotcspot
tdotcspot

Reputation: 345

Filtered Dropdown (using select) With Accumulated Totals (ng-repeat)

Hoping someone might be able to shed some light on my problem. I have an AgularJS dropdown list that displays a number of Users. Depending on what user you select, it will show some data which is referenced by the user's id. Everything works great! No problems there.

I've wanted to try to take these results and do some math operations to it. In my example below, when a user is selected, it will show a day of the week, and a "score". I'd like to try to accumulate the score at the end of each row.

FIDDLE: http://jsfiddle.net/bfoyhycy/1

    <tr ng-repeat="eachItem in Data |filter: { id: selectedOption.id }">
        <td>{{eachItem.day}}</td>
        <td>{{eachItem.score}}</td>
        <td> <!---- NO IDEA WHAT TO DO HERE ----> </td>
    </tr>

I thought I could reference the Data and use it's index, but this won't work because I'm filtering it based on the 'id'. So the accumulated total will be correct for the first user, but incorrect for the rest (this can be seen if you select the user "Frank").

FIDDLE: http://jsfiddle.net/bfoyhycy/2/

    <tr ng-repeat="eachItem in Data |filter: { id: selectedOption.id }">
        <td>{{eachItem.day}}</td>
        <td>{{eachItem.score}}</td>
        <td>{{Data[$index-1].score}}</td>
    </tr>

I'd like to know if there's a way to get the previous row value during an ng-repeat? I initially thought you could do a {{eachItem[$index-1].score}} but apparently you can't. If anyone has any ideas how to go about this problem, it would be very appreciated! Please let me know if I need to provide more information. Hopefully that all made sense!

Thanks! T

Upvotes: 1

Views: 447

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

You can assign the filtered items to a variable named filteredData like this...

<tr ng-repeat="eachItem in filteredData = (Data |filter: { id: selectedOption.id })">

And now you can use $index properly...

<td>{{ filteredData[$index-1].score }}</td>

To get a true running total, you actually need to do a bit more. One way to do it is with ngInit, although I'll have to say it's getting pretty hacky at this point, but it works...

    <tr ng-repeat="eachItem in filteredData = (Data |filter: { id: selectedOption.id })" 
      ng-init="eachItem.runningTotal = filteredData[$index-1].runningTotal + eachItem.score">
        <td>{{eachItem.day}}</td>
        <td>{{eachItem.score}}</td>
        <td>{{eachItem.score + filteredData[$index-1].runningTotal}}</td>
    </tr>

Live Demo

Perhaps a better solution is to create a custom filter that outputs a filtered array with precalculated running totals.

Upvotes: 1

Related Questions