簡體   English   中英

使用AngularJS過濾JSON數據

[英]Filter JSON Data with 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);
    }
}

但是,還有其他的Angular-thonic方法可以做到這一點嗎? 我一直在尋找過濾器,但無法找出一種簡單的方法(除了像上面那樣遍歷綁定數據之外)來做到這一點。

更新:

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>

您可以像這樣創建自定義過濾器

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中,您可以像這樣對數組建立索引: UPDATED:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM