JVG*_*JVG 131 angularjs angularjs-ng-repeat
我正在运行一个简单ng-repeat的JSON文件,并希望得到类别名称.大约有100个对象,每个对象属于一个类别 - 但只有大约6个类别.
我目前的代码是这样的:
<select ng-model="orderProp" >
<option ng-repeat="place in places" value="{{place.category}}">{{place.category}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)
输出是100个不同的选项,大多数是重复的.如何使用Angular检查是否{{place.category}}已存在,如果已存在则不创建选项?
编辑:在我的javascript中$scope.places = JSON data,只是为了澄清
jpm*_*rin 141
您可以使用AngularUI中的唯一过滤器(此处提供的源代码:AngularUI唯一过滤器)并直接在ng-options(或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>
Run Code Online (Sandbox Code Playgroud)
Mik*_*ard 37
或者您可以使用lodash编写自己的过滤器.
app.filter('unique', function() {
return function (arr, field) {
return _.uniq(arr, function(a) { return a[field]; });
};
});
Run Code Online (Sandbox Code Playgroud)
a8m*_*a8m 30
您可以在angular.filter模块中
使用"unique"(别名:uniq)过滤器
用法:colection | uniq: 'property'
您还可以按嵌套属性进行过滤: colection | uniq: 'property.nested_property'
你能做什么,是这样的......
function MainController ($scope) {
$scope.orders = [
{ id:1, customer: { name: 'foo', id: 10 } },
{ id:2, customer: { name: 'bar', id: 20 } },
{ id:3, customer: { name: 'foo', id: 10 } },
{ id:4, customer: { name: 'bar', id: 20 } },
{ id:5, customer: { name: 'baz', id: 30 } },
];
}
Run Code Online (Sandbox Code Playgroud)
HTML:我们按客户ID过滤,即删除重复的客户
<th>Customer list: </th>
<tr ng-repeat="order in orders | unique: 'customer.id'" >
<td> {{ order.customer.name }} , {{ order.customer.id }} </td>
</tr>
Run Code Online (Sandbox Code Playgroud)
结果
客户名单:
foo 10
bar 20
baz 30
Edu*_*tiz 15
这段代码适合我.
app.filter('unique', function() {
return function (arr, field) {
var o = {}, i, l = arr.length, r = [];
for(i=0; i<l;i+=1) {
o[arr[i][field]] = arr[i];
}
for(i in o) {
r.push(o[i]);
}
return r;
};
})
Run Code Online (Sandbox Code Playgroud)
然后
var colors=$filter('unique')(items,"color");
Run Code Online (Sandbox Code Playgroud)
如果要列出类别,我认为您应该在视图中明确说明您的意图。
<select ng-model="orderProp" >
<option ng-repeat="category in categories"
value="{{category}}">
{{category}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
在控制器中:
$scope.categories = $scope.places.reduce(function(sum, place) {
if (sum.indexOf( place.category ) < 0) sum.push( place.category );
return sum;
}, []);
Run Code Online (Sandbox Code Playgroud)