celsomtrindade
celsomtrindade

Reputation: 4671

AngularJs error when usin track by $index with filter in a ng-repeat

I'm having trouble when using a filter on a ng-repeat list and track by $index. I have a list of hotels and need to filter it by the city name.

The filter is working fine, this isn't the problem. The problem is the rendered list AFTER the filter. There is 2 situations at the moment:

See this plunkr for example: https://plnkr.co/edit/J1QQCM?p=preview

If you filter by 'New York', the list will have only 4 results, but doesn't reorder the list to show the results from the city 'New York'. And this only happens when using track by $index.

This is the html I'm using:

<li ng-repeat="item in vm.mainList | filter:{location:filterLocation} track by $index">...</li>

And the array is something very basic, like this:

{
    "id": 0,
    "title": "Hotel The Mirage (Hotel & Casino)",
    "location": "Las Vegas, USA"
},
{
    "id": 1,
    "title": "Wynn Las Vegas",
    "location": "Las Vegas, USA"
},[...]~

Note: I know I could solve this by using track by item.id, but this is a simple example. On the actual list I have more nested array and eventually I'll end up with id repeting. So I need to be able to use track by $index.

Upvotes: 2

Views: 5115

Answers (1)

Casey
Casey

Reputation: 3353

It's not working because you're using the one-time binding syntax.

I've forked your plunkr and used the regular syntax and it works: https://plnkr.co/edit/mLaiqsrk9uUqnaYe308F?p=preview

  <ul>
    <li ng-repeat="item in vm.mainList | filter:{location:filterLocation} track by $index">
        <h4>{{ item.title }} - {{$index}}</h4>
        <p>{{ item.location }}</p>
    </li>
  </ul>

Upvotes: 4

Related Questions