2013-12-11 48 views
0

我将JSON对象绑定到列表,但我只想为每个用户显示一个(第一个,因为结果是有序的)项目。我回来的JSON是每个项目,用户对象作为一个属性(item.user.username等)。有了jQuery,我会做类似的:使用AngularJS过滤JSON数据

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方法来做到这一点?我一直在寻找过滤器,但不能找出一个简单的方法(除了迭代上面的绑定数据)来做到这一点。

UPDATE:

AngularJS代码是一个有点多后,但基本上我在我的控制器JSON对象,我通过的$ HTTP的API礼貌和ItemFactory获得的$ scope.items阵列,并非常基本的HTML来显示的东西:

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

我可以看到你的角码吗?也将显示这个HTML? – Fresheyeball

+0

理想情况下把代码放入jsfiddle.net或带有示例数据的plunker中......虽然 – charlietfl

回答

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

这里基本上就是我现在用上面发布的jQuery所做的 - 只是希望这是一个解决的角度问题,不需要我遍历整个数组,因为angularjs使它很容易消耗JSON数据。 –

+0

然后你可以在你的html中索引这个数组,就像我上面发布的那样。 {{项目[0] .something}}将工作得很好。 – zfor

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

这仍然遍历每个项目(再次)。由于ng-repeat已经迭代了这些项目,我正在寻找一种方法来迭代一次以提高效率。过滤器的想法应该能够让我到那里,虽然,也许只是检查每个项目,因为它传递给过滤器(不知道过滤器是一次应用于数组还是每次应用一次)。 –