Skip to main content
 首页 » 编程设计

angularjs之如何在 Angular 中使用 ng-options 过滤选择

2025年02月15日21itcoder

我编写了以下 Angular 应用程序的概念验证,该应用程序允许一个人投票给美国总统。

<!DOCTYPE html> 
<html ng-app="ElectionApp""> 
<head> 
    <title></title> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script> 
    <script> 
        var ElectionApp = angular.module("ElectionApp", []); 
        var ElectionController = ElectionApp.controller("ElectionController", [function () { 
            // Pretend that this data came from an outside data-source. 
            this.candidates = { 
                "14837ac3-5c45-4e07-8f12-5771f417ca4c": { 
                    name: "Alice", 
                    gender: "female" 
                },"333eb217-c8d1-4b94-91a4-22a3770bbb22": { 
                    name: "Bob", 
                    gender: "male" 
                } 
            }; 
            this.vote = function () { 
                // TODO: Record the user's vote. 
            }; 
        }]); 
    </script> 
</head> 
<body ng-controller="ElectionController as ctrl"> 
    Who would you like to elect President? <br /> 
    <select 
        ng-model="ctrl.selection" 
        ng-options="person as person.name for (id, person) in ctrl.candidates | filter{gender:'female'}"> 
    </select> 
    <input type="button" value="Vote!" ng-submit="ctrl.vote();" /> 
 
    <h2>Candidate Profiles</h2>     
    <div ng-repeat="candidate in ctrl.candidates"> 
        {{candidate.name}}, {{candidate.gender}} 
    </div> 
</body> 
</html> 

我的投票应用程序显示候选人姓名列表以及每个候选人的个人资料,在这种情况下,由候选人的姓名和性别组成。

出于本问题的目的,请假设要从中选择的候选人名册是从远程数据源获取的,但将遵循与示例相同的格式。

假设在即将举行选举前不久,通过了一项宪法修正案,规定下一任美国总统必须是女性。假设数据源无法及时更新以进行选举,老板对我说,“我听说在Angular中,您可以使用过滤器随意选择数据源中的哪些项目出现在表单上。使之发生!”

继我在网上看到的一些示例之后,我编写了上面的代码,但它不再显示任何候选人。我做错了什么?

如何使用 Angular 过滤器过滤选择列表中的选项?

请您参考如下方法:

filter只能对数组进行操作。

但是您可以创建自定义过滤器:

ElectionApp.filter('females', [ function() { 
    return function (object) { 
        var array = []; 
        angular.forEach(object, function (person) { 
            if (person.gender == 'female') 
                array.push(person); 
        }); 
        return array; 
    }; 
}]); 

然后写
ng-options="name as person.name for (id, person) in ctrl.candidates | females">