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

这一生的挚爱 提交于 2019-12-12 00:34:06

问题


I'm working with AngularJS and trying to create a filter to search properties.

I've got a select box like this:

<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>

This is the unique function:

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;
}; });

How can I get filtered.length to work?

Here's my JSFiddle


回答1:


Here's a solution:

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

Create a filter that returns objects with count (number of times they were in the original list):

    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;
        };
    });

Use that filter in your 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>


来源:https://stackoverflow.com/questions/29172928/how-to-count-unique-results-based-on-a-particular-properties-within-ng-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!