本文介绍了如何让 ng-repeat 过滤掉重复的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个 JSON 文件上运行一个简单的 ng-repeat 并且想要获取类别名称.大约有 100 个对象,每个对象都属于一个类别——但只有大约 6 个类别.

I'm running a simple ng-repeat over a JSON file and want to get category names. There are about 100 objects, each belonging to a category - but there are only about 6 categories.

我目前的代码是这样的:

My current code is this:

<select ng-model="orderProp" >
  <option ng-repeat="place in places" value="{{place.category}}">{{place.category}}</option>
</select>

输出是 100 个不同的选项,大部分是重复的.如何使用 Angular 检查 {{place.category}} 是否已经存在,如果已经存在则不创建选项?

The output is 100 different options, mostly duplicates. How do I use Angular to check whether a {{place.category}} already exists, and not create an option if it's already there?

在我的javascript中,$scope.places = JSON data,只是为了澄清

edit: In my javascript, $scope.places = JSON data, just to clarify

推荐答案

您可以使用来自 AngularUI 的 unique 过滤器(源代码可在此处获得:AngularUI 唯一过滤器)并直接在 ng-options(或 ng-重复).

You could use the unique filter from AngularUI (source code available here: AngularUI unique filter) and use it directly in the ng-options (or ng-repeat).

<select ng-model="orderProp" ng-options="place.category for place in places | unique:'category'">
    <option value="0">Default</option>
    // unique options from the categories
</select>

这篇关于如何让 ng-repeat 过滤掉重复的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 23:38