如何根据ng-options中的特定属性计算唯一结果 [英] How to count unique results based on a particular properties within ng-options

查看:88
本文介绍了如何根据ng-options中的特定属性计算唯一结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

这是独特的功能:

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/

创建一个过滤器,该过滤器返回带有计数(对象在原始列表中的次数)的对象:

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

在HTML中使用该过滤器:

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>

这篇关于如何根据ng-options中的特定属性计算唯一结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆