我在 ng-repeat
列表和 track by $index
上使用过滤器时遇到问题。我有一个酒店列表,需要按城市名称对其进行过滤。
过滤器工作正常,这不是问题。问题是过滤器之后呈现的列表。目前有2种情况:
1:如果不使用
track by
或使用track by item.id
,则一开始不会出现错误,但如果我选择一个选项,我'会得到错误:[ngRepeat:dupes]
,可以使用track by $index
解决。2:如果使用
track by $index
,则无论我选择哪个选项,都不会出现错误。但是,该列表无法正确更新。当我选择一个城市时,列表将显示结果数量,但不显示正确结果。例如,共有 12 家酒店,选择后只有 4 条结果。该列表将有 4 个结果,但它不会更新结果,它只是将列表减少到 4 个结果,但保持相同的顺序。
请参阅此 plunkr 例如:https://plnkr.co/edit/J1QQCM?p=preview
如果您按“纽约”进行过滤,列表将只有 4 个结果,但不会重新排序列表以显示“纽约”城市的结果。这种情况仅在使用 track by $index
时发生。
这是我正在使用的 html:
<li ng-repeat="item in vm.mainList | filter:{location:filterLocation} track by $index">...</li>
数组是非常基本的东西,如下所示:
{
"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 usetrack by $index
.
最佳答案
它不起作用,因为您使用的是一次性绑定(bind)语法。
我已经 fork 了你的 plunkr 并使用了常规语法,它可以工作: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>
关于在 ng-repeat 中使用带有过滤器的 $index 跟踪时出现 AngularJs 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36201694/