如何在angularJS中为对象数组使用过滤器?

How can I use filter for array of object in angularJS?

本文关键字:数组 过滤器 对象 angularJS      更新时间:2023-09-26

我得到一个json数组,如:

{"1":{"postid":1,"name":"akash","date":"28 Jul 2014"}
 ,"2":{"postid":2,"name":"rajat","date":"28 Jul 2014"}
 ,"3":{"postid":3,"name":"rahul","date":"28 Jul 2014"}}

我正在尝试使用下面的代码来过滤这个数组:-

<input type="text"  ng-model="queryfield" />
<div class="privacy_wrp data"
     ng-repeat="res in faqallhtml | filter:queryfield"
     id="{{res.postid}}">
<h4> {{res.name}}</h4>  
 <span class="date">{{res.date}}</span> </p>

但是我无法过滤结果。当我试图通过此代码进行过滤时,没有发生任何事情。

使用underscore.js中的_.values()函数使其工作

http://jsfiddle.net/8MVLJ/981/

控制器:

$scope.faqallhtml = {
"1":{"postid":1,"name":"akash","date":"28 Jul 2014"},
"2":{"postid":2,"name":"rajat","date":"28 Jul 2014"},
"3":{"postid":3,"name":"rahul","date":"28 Jul 2014"}
};
$scope.faqallhtmlValues = _.values($scope.faqallhtml);
HTML:

ng-repeat="res in faqallhtmlValues | filter:queryfield"

try this

<div class="privacy_wrp data" ng-repeat="res in faqallhtml | filter:{'property':queryfield}" id="{{res.postid}}">

它为我工作时,使用数组的对象

正如答案中所述,您需要获取这些值,在这种情况下无需加载额外的库。您可以简单地手动执行

<div class="privacy_wrp data" ng-repeat="res in searchFilter(faqallhtml)|filter:queryfield" id="{{res.postid}}">

其中searchFilter将其转换为数组:

$scope.searchFilter = function(items) {
    var data = [];
    angular.forEach(items, function(value, key) {
      data.push(value)
    })
    return data;
};
工作代码