问题描述
我绑定JSON对象到列表,但我只想要展示一个(第一,因为结果排序)每个用户的项目。我取回JSON是每个项目,与用户对象作为一个属性(item.user.username等)。用jQuery我会做这样的事情:
VAR ARR = ... JSON对象...
变种seen_users = [];
变种项= [];
$。每个(ARR,功能(I,项目){
如果(!$。inArray(item.user.id,ARR)=== -1){
items.push(项目);
seen_users.push(item.user.id);
}
}
但有一个更加角thonic办法做到这一点?我一直在寻找,但过滤器(不是通过像上面绑定的数据迭代等),要做到这一点想不通一个简单的方法。
更新:
AngularJS code是有点多发帖,但基本上我有我的控制器JSON对象,我通过的$一个API礼貌HTTP和ItemFactory得到一个$ scope.items数组,pretty基本的HTML来显示的东西:
< UL ID =项目>
<李班=项数据-NG-重复=中的项项>
{{item.title}} | {{item.posted}}
< /李>
< / UL>
您可以创建一个这样的自定义过滤器
app.filter('myFilter',[功能(){
复位功能(ARR){
变种seen_users = [];
变种项= [];
$。每个(ARR,功能(I,项目){
如果(!$。inArray(item.user.id,ARR)=== -1){
items.push(项目);
seen_users.push(item.user.id);
}
});
返回seen_users;
};
}]);
而在这样的模板中使用它
<李班=项数据-NG-重复=项(项目| myFilter)>
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. The JSON I'm getting back is per item, with a user object as a property (item.user.username, etc.). With jQuery I'd do something like:
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? 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:
<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)">
这篇关于过滤JSON数据与AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!