【问题标题】:Filtering an Angular 1.2 ng-repeat with "track by" by a boolean property通过布尔属性过滤带有“track by”的Angular 1.2 ng-repeat
【发布时间】:2014-02-20 09:03:38
【问题描述】:

我正在尝试根据布尔属性的值过滤一些列表项,但无论我做什么,都会显示整个列表。我尝试过的一些东西已经被破坏了,以至于什么都没有显示,但这既不是这里也不是那里。我无法按要求进行过滤:

$scope.attendees = [
     {"firstname":"Steve",    "lastname":"Jobs",  "arrived":true,  "id":1}
    ,{"firstname":"Michelle", "lastname":"Jobs",  "arrived":false, "id":2}
    ,{"firstname":"Adam",     "lastname":"Smith", "arrived":true,  "id":3}
    ,{"firstname":"Megan",    "lastname":"Smith", "arrived":false, "id":4}
    ,{"firstname":"Dylan",    "lastname":"Smith", "arrived":false, "id":5}
    ,{"firstname":"Ethan",    "lastname":"Smith", "arrived":false, "id":6}
];

使用以下 ng-repeat 过滤:

<ul>
    <li ng-repeat="person in attendees track by person.id | filter:arrived:'false'">
            {{person.lastname}}, {{person.firstname}}
    </li>
</ul>

我觉得我已经尝试了所有可以找到引用的排列,其中大部分来自各种 StackOverflow 搜索结果:

  • filter:'arrived'
  • filter:arrived
  • filter:'person.arrived'
  • filter:person.arrived
  • filter:{arrived:true}
  • filter:{arrived:'true'}
  • filter:{person.arrived:true}
  • filter:{person.arrived:'true'}

我也尝试过创建自定义过滤功能:

$scope.isArrived = function(item) {
    return item.arrived;
};

并如此应用它:

  • filter:isArrived
  • filter:'isArrived'
  • filter:{isArrived(person)}
  • filter:isArrived(person)
  • filter:'isArrived(person)'

这些似乎都不起作用。我错过了什么?

Here's a plnkr that demonstrates my problem.

【问题讨论】:

    标签: angularjs angularjs-ng-repeat


    【解决方案1】:

    track by 需要在表达式的末尾:

    <li ng-repeat="person in attendees | filter: {arrived: false } track by person.id">
    

    【讨论】:

    • 翻页真烦人,浪费30分钟。我希望它使用trackBy: .. 并且“像其他所有东西一样”正常运行。
    • 这是非常重要的一点。通过大多数前导字符基本相同的唯一值进行跟踪,我们得到了重复错误,因为跟踪不是表达式中的最后一个。非常模糊的错误imo。
    【解决方案2】:

    @Gruff's answer 是对的,但只是从官方来源给出答案:

    来自 Angular ng-repeat docs

    注意:track by 必须始终是最后一个表达式

    <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
      {{model.name}}
    </div>
    

    它也出现在文档的“参数”部分:

    请注意,跟踪表达式必须排在最后,在任何过滤器之后, 和别名表达式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-14
      • 2014-12-27
      • 2023-03-29
      • 1970-01-01
      • 2014-05-30
      • 2016-07-26
      • 2013-07-13
      • 1970-01-01
      相关资源
      最近更新 更多