p-glog
Last Updated: February 25, 2016
·
30.71K
· cironunes

AngularJS: Using trackBy with filters in an ng-repeat

Since the version 1.1.4, it's considered an error to have two identical items in a collection that is fed into the repeater. So, the following code will thrown an exception:

<ul>
    <li ng-repeat="item in [1, 2, 3, 3]">
        {{ item }}
    </li>
</ul>

That's because the new track by expression was introduced for custom tracking items. To fix our code, we could use it like that:

<ul>
    <li ng-repeat="item in [1, 2, 3, 3] track by $index">
        {{ item }}
    </li>
</ul>

The thing is, as soon as you try to add filters to your ngRepeat they wouldn't work:

<input type="text" ng-model="searchText">
<ul>
    <li ng-repeat="item in [1, 2, 3, 3] track by $index | filter:searchText">
        {{ item }}
    </li>
</ul>

That's because filters should be applied before the track by expression. It's in the docs of ngRepeat but as it makes a lot of confusion for beginners it's worth remembering that. The working code would look like that:

<input type="text" ng-model="searchText">
<ul>
    <li ng-repeat="item in [1, 2, 3, 3] | filter:searchText track by $index">
        {{ item }}
    </li>
</ul>

You can play with this code examples in this plunker

2 Responses
Add your response

18975

Thanks for posting this. Helped me figure out why my filters weren't working anymore.

over 1 year ago ·
24572

Thanks. Solved my issue in 30 seconds because of this.

--Will

over 1 year ago ·