我有以下几点:
$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-options呢?
ng-options
要删除重复项,可以使用AngularUI 的 唯一 过滤器(源代码在这里:AngularUI唯一过滤器),然后直接在ng-options(或ng- repeat)中使用它。
在这里查看更多: 独特的东西
json结构中也存在语法错误。
工作守则
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; }; });