如何根据 ng-options 中的特定属性计算唯一结果

How to count unique results based on a particular properties within ng-options

我正在使用 AngularJS 并尝试创建一个过滤器来搜索属性。

我有一个这样的 select 盒子:

<select 
    class="selectBox" 
    multiple="multiple" 
    ng-model="selectedSubArea" 
    ng-options="property.SubArea as (property.SubArea + ' ('+ filtered.length +')') for property in filtered = (properties | unique:'SubArea') | orderBy:'SubArea'">
</select>

这是独特的功能:

myApp.filter('unique', function() {
return function(input, key) {
    var unique = {};
    var uniqueList = [];
    for(var i = 0; i < input.length; i++){
        if(typeof unique[input[i][key]] == "undefined"){
            unique[input[i][key]] = "";
            uniqueList.push(input[i]);
        }
    }
    return uniqueList;
}; });

如何让 filtered.length 工作?

这是我的 JSFiddle

这是一个解决方案:

http://jsfiddle.net/odpw6c6q/16/

创建一个过滤器,returns 个对象的计数(它们在原始列表中的次数):

    myApp.filter('uniqueWithCount', function() {
        return function(input, key) {
            var unique = {};
            var uniqueList = [];
            var obj, val;
            for(var i = 0; i < input.length; i++){
                val = input[i][key];
                obj = unique[val];
                if (!obj) {
                    obj = unique[val] = {data: input[i], count: 0};
                    uniqueList.push(obj);
                }
                obj.count++;
            }
            return uniqueList;
        };
    });

在您的 HTML 中使用该过滤器:

<select class="form-control" multiple="multiple" ng-model="selectedSubArea"
ng-options="property.SubArea as (item.data.SubArea + ' ('+ item.count +')') for item in filtered = (properties | uniqueWithCount:'SubArea') | orderBy:'SubArea'"></select>