如何使用 ng-options 从 JSON 对象 属性 中获取不同的下拉选项值并将其用作过滤器?

How to get distinct values from JSON object property for dropdown options using ng-options and use it as a filter?

我正在尝试制作一个多 selection 列表,上面有一个下拉列表作为过滤器。上面下拉列表的值包含部门名称,然后根据上面 selected 部门在下面的列表中显示其员工。

这是我的范围:

var self = this;
 self.users = [{ department: "A", name: "santos" }, { department: "B", name: "suarez" }, { department: "C", name: "domingo" }, { department: "A", name: "james" }, { department: "B", name: "black" }, { department: "C", name: "de leon" }, { department: "A", name: "dela cruz" }, { department: "B", name: "robertson" }, { department: "C", name: "williams" }, { department: "A", name: "crawford" },
 { department: "B", name: "garcia" }, { department: "C", name: "navarro" }, { department: "A", name: "lim" }, { department: "B", name: "lee" }, { department: "C", name: "vasquez" }, { department: "A", name: "montano" }, { department: "B", name: "trump" }, { department: "C", name: "arroyo" }, { department: "A", name: "aquino" }, { department: "B", name: "duterte" }];

这是我的 html:

<select class="form-control" ng-options="item as item.department for item in formsDcfCtrl.users" ng-model="departmentsList">
 <option value="" selected>Departments</option>
 </select>

<select multiple class="form-control" ng-options="x as x.name for x in formsDcfCtrl.users | filter:departmentsList" ng-model="usersList"></select>

但我得到不同的结果:

下面列表的值很好,但下拉列表的值基于数组中部门的每个值:

当我从下拉列表中 select 一个字母(部门)时,而不是 ALL 例如,部门 A 中的名称将显示在在下面的列表中,仅显示 selected 下拉值中该特定元素的部门特定值的名称。我该如何解决?

您可以尝试使用下面提到的过滤器来解决它。还要使用此 plunker link.

检查给定的示例工作场景

模板:

ng-options="item as item.department for item in users | unique:'department'"

控制器:

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