简体   繁体   中英

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:

  • 1: If not using track by or using track by item.id there is no error at the beggining, but if I select an option I'll get the error: [ngRepeat:dupes] , which can be solved by using track by $index .

  • 2: If using track by $index there is no errors, no matter what option I select. BUT, the list doesn't update properly. When I select one city the list will show the amount of results, but not the correct results. For example, if there is a total of 12 hotels and after the select there is only 4 results. The list will have 4 results, but it's not updating the results, it only reduce the list to 4 results but keeps the same order.

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 .

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM