使用AngularJS过滤JSON数据

Filter JSON Data with AngularJS

本文关键字:数据 JSON 过滤 AngularJS 使用      更新时间:2024-06-24

我将JSON对象绑定到一个列表,但我只想为每个用户显示一个(第一个,因为结果是有序的)项。我得到的JSON是按项目的,以用户对象为属性(item.user.username等)

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

但是,有没有一种更具角度的丁字裤方式可以做到这一点?我一直在研究过滤器,但无法找到一种简单的方法(除了像上面那样迭代绑定数据)来做到这一点。

更新:

AngularJS代码有点太多了,但基本上我的控制器中有一个JSON对象的$scope.items数组,我通过$http和ItemFactory提供的API获得了它,还有非常基本的HTML来显示内容:

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

您可以创建类似的自定义过滤器

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)">

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