Javascript ng-repeat with track by 和 filter 以及 orderBy 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29608450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:39:39  来源:igfitidea点击:

ng-repeat with track by and filter and orderBy not working

javascriptangularjsangularjs-scopeangularjs-ng-repeat

提问by PatrickB

I have this code.

我有这个代码。

http://jsfiddle.net/0tgL7u6e/

http://jsfiddle.net/0tgL7u6e/

JavaScript

JavaScript

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.nameFilter = '';
    $scope.contacts = [
        {name: 'GHI'},
        {name: 'DEF'},
        {name: 'ABC'},
        {name: 'JKL'}
    ];
}

View

看法

<div ng-controller="MyCtrl">
    <div><input type="text" ng-model="nameFilter" placeholder="Search..." /></div>
    <p ng-repeat="contact in contacts track by $index | filter: nameFilter | orderBy: name">{{ contact.name }}</p>
</div>

I don't know why the order is not working and why the filter is not working.

我不知道为什么订单不起作用以及为什么过滤器不起作用。

At another question, I've read about something that objects can't be filtered or ordered. But I have an array of the objects above. Also, it should work!?

在另一个问题上,我读过一些对象无法过滤或排序的内容。但是我有一个上面的对象数组。此外,它应该工作!?

What's the problem?

有什么问题?

回答by Sajeetharan

To use tracking with filters, the track by expression has to be added after the filter.

要使用带过滤器的跟踪,必须在过滤器后添加跟踪表达式。

<p ng-repeat="contact in contacts | orderBy: 'name' | filter: nameFilter  track by $index">{{ contact.name }}</p>

Here is the working fiddle

这是工作 fiddle

回答by Reza

you have to change the code to the following one

您必须将代码更改为以下代码

<div ng-controller="MyCtrl">
    <div><input type="text" ng-model="nameFilter" placeholder="Search..." /></div>
    <p ng-repeat="contact in contacts  | orderBy: name | filter: nameFilter track by $index ">{{ contact.name }}</p>
</div>