1

I have an array of objects that have a "Category" property. In my ng-repeat, I am creating a group by conditionally showing a header row with the category name if it is different that the previous value by using items[$index - 1] to check the previous value. This works, but if I apply an orderBy filter, it would seem that $index doesn't reflect the new order. What am I doing wrong?

adam0101
  • 29,096
  • 21
  • 96
  • 174

1 Answers1

5

As soon as I posted this, I realized what might fix it. I added track by item.itemId and it started acting as expected.

<div class="row" ng-repeat="item in items track by item.itemId | filter: searchTerms | orderBy:['Category1', 'Category2']">
  <div class="rowHeader" ng-show="$index == 0 || item.Category1 != items[$index -1].Category1">
    {{item.Category1}}
  </div>
</div>
adam0101
  • 29,096
  • 21
  • 96
  • 174
  • 1
    It's not working for me, I always get a random previous object. Also, when I put the "track by" statement before the orderBy pipe, my list is not ordered. When I put "track by" after the orderBy, the list is ordered. – tomahim Nov 12 '15 at 10:17
  • As seen in [this answer](http://stackoverflow.com/a/15413253/4519548), you have to be aware of orderBy messing up the elements and create a correct array instead. – Rick Wolff Jan 23 '17 at 12:18