使用AngularJS过滤JSON数据

时间:2013-12-11 21:50:45

标签: javascript json angularjs

我将JSON对象绑定到列表,但我只想显示每个用户一个(第一个,因为结果是有序的)项目。我回来的JSON是每个项目,用户对象作为属性(item.user.username等)。使用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);
    }
}

但是,有更多的角度 - thonic方法吗?我一直在寻找过滤器,但无法找到一个简单的方法(除了迭代上面的绑定数据)来做到这一点。

更新:

AngularJS代码有点发布,但基本上我在我的控制器中有一个$ scope.items JSON对象数组,我通过API提供了$ http和一个ItemFactory,以及非常基本的HTML来显示东西:

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

2 个答案:

答案 0 :(得分:1)

您可以像这样创建自定义过滤器

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;
    };
}]);

并在模板中使用它

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

答案 1 :(得分:0)

在你的html中,你可以像这样索引你的数组: 的更新:

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

你的脚本应该是:

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

还有其他几种方法可以做到这一点。如果您希望它是动态的(例如,如果您希望稍后按需显示更多项目:

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

这个脚本就像:

$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]);
};