简体   繁体   English

使用AngularJS过滤JSON数据

[英]Filter JSON Data with AngularJS

I'm binding JSON objects to a list, but I only want to show one (the first, since the results are ordered) item per user. 我将JSON对象绑定到一个列表,但是我只想为每个用户显示一个(第一个,因为结果是有序的)项目。 The JSON I'm getting back is per item, with a user object as a property (item.user.username, etc.). 我要返回的JSON是每个项目的内容,带有用户对象作为属性(item.user.username等)。 With jQuery I'd do something like: 使用jQuery,我会做类似的事情:

var arr = ... JSON objects ...
var seen_users = [];
var items = [];
$.each(arr, function(i, item){
    if (!$.inArray(item.user.id, arr) === -1){
        items.push(item);
        seen_users.push(item.user.id);
    }
}

But is there a more Angular-thonic way to do this? 但是,还有其他的Angular-thonic方法可以做到这一点吗? I've been looking at filters but can't figure out an easy way (other than iterating through the bound data like above) to do this. 我一直在寻找过滤器,但无法找出一种简单的方法(除了像上面那样遍历绑定数据之外)来做到这一点。

UPDATE: 更新:

AngularJS code is a little much to post, but basically I have a $scope.items array of JSON objects in my controller that I get via an API courtesy of $http and an ItemFactory, and pretty basic HTML to display things: AngularJS代码要发布很多,但是基本上我在控制器中有一个$ scope.items JSON对象数组,我可以通过$ http和ItemFactory的API获得该数组,还可以使用相当基本的HTML来显示内容:

<ul id="items">
    <li class="item" data-ng-repeat="item in items">
       {{item.title}} | {{item.posted}}
    </li>
</ul>

You can create a custom filter like this 您可以像这样创建自定义过滤器

app.filter('myFilter', [function () {
    return function (arr) {
        var seen_users = [];
        var items = [];
        $.each(arr, function (i, item) {
            if (!$.inArray(item.user.id, arr) === -1) {
                items.push(item);
                seen_users.push(item.user.id);
            }
        });
        return seen_users;
    };
}]);

And use it in the template like this 并在这样的模板中使用它

<li class="item" data-ng-repeat="item in (items | myFilter)">

In your html you can index your array like this: UPDATED: 在您的html中,您可以像这样对数组建立索引: UPDATED:

<ul>
    <li>
      {{item[0].title}} | {{item[0].posted}}
    </li>
</ul>

and you script should be like: 您的脚本应类似于:

$scope.items = []; // with your data in it.

There is a couple of other way to do this. 还有其他两种方法可以做到这一点。 If you want it to be dynamic (eg If you want to display more items on demand later: 如果您希望它是动态的(例如,如果您以后想要显示更多项目,则:

<span data-ng-repeat="item in displayItems">
 {{item.user.id}}
</span>

The script for that would be like: 脚本如下:

$scope.items = []; // this is your original array with all the data in it.
$scope.displayItems = []; // this is an empty array that a function will fill up with        data
myFunction = function(){
   // put data selection logic here
   $scope.displayItems.push($scope.items[i]);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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