从角JS删除重复NG选项/ NG重复 [英] Removing duplicates from Angular JS ng-options / ng-repeat
本文介绍了从角JS删除重复NG选项/ NG重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
确定我有以下几点:
$scope.jsonmarkers = [{
"name": "Jeff",
"type": "Organisation + Training Entity",
"userID": "1"
}, {
"name": "Fred",
"type": "Organisation + Training Entity",
"userID": "2"
}];
和这在我的HTML:
<select id="typeselect" multiple ng-options="accnts.type for accnts in jsonmarkers" ng-model="accnt" ng-change="changeaccnt(accnt.type)"></select>
我如何去匹配的类型,只有它呼应每一次亮相在NG选项?
how do i go about matching the type and only echoing it once per appearance in the ng-options?
推荐答案
有关删除重复,你可以从AngularUI(来源$ C $ C可以在这里使用唯一过滤器:的 AngularUI独特的过滤),并直接在NG使用-options(或NG-重复)。
For removing duplicates 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).
在这里寻找更多: 独特性和放大器;东西
Look here for more: Unique & Stuff
也有一个在JSON结构的语法错误。
Also there's a syntax error in json structure.
Working Code
HTML
<div ng-app="app">
<div ng-controller="MainController">
<select id="typeselect" ng-options="accnts.type for accnts in jsonmarkers | unique:'type'" ng-model="accnt" ng-change="changeaccnt(accnt.type)" multiple></select>
</div>
</div>
脚本
var app = angular.module("app", []);
app.controller("MainController", function ($scope) {
$scope.jsonmarkers = [{
"name": "Jeff",
"type": "Organisation + Training Entity",
"userID": "1"
}, {
"name": "Fred",
"type": "Organisation + Training Entity",
"userID": "2"
}];
});
app.filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
这篇关于从角JS删除重复NG选项/ NG重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文