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

Dan*_*don 21 angularjs ng-options angularjs-ng-options

我写了一个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>
Run Code Online (Sandbox Code Playgroud)

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

出于这个问题的目的,请假装可供选择的候选人名单来自远程数据源,但将采用与示例相同的格式.

假设在选举前不久,通过宪法修正案,强制下一任美国总统必须是女性.假设数据源无法及时更新,并且老板对我说,"我听说过使用Angular,您可以使用过滤器随意选择数据源中的哪些项目出现在表单上.发生!"

下面是我在线看到的一些例子,我已经编写了上面的代码,但它不再显示任何候选者.我做错了什么?

如何使用角度滤镜过滤选择列表中的选项?

Ben*_*ost 22

你只是在filter关键字后忘了":".

<select 
    ng-model="ctrl.selection"
    ng-options="person as person.name for person in ctrl.candidates | filter:{gender:'female'}">
</select>
Run Code Online (Sandbox Code Playgroud)


小智 18

也许有点晚了,但对于寻找信息的其他人我正在使用这个.

$scope.deliveryAddresses = data; 
Run Code Online (Sandbox Code Playgroud)

数据是复杂的Json id,名称和城市从我的Angular控制器中通过$ http.get从webapi收到

我在我的Html页面中使用它与下面的代码片段

ng-options="address.name for address in deliveryAddresses | filter:{name:search} track by address.id
Run Code Online (Sandbox Code Playgroud)

其中search是对文本框的引用.简单高效.

希望它可以帮助某人.


wer*_*ero 14

filter 只能在阵列上运行.

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

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

然后写

ng-options="name as person.name for (id, person) in ctrl.candidates | females">
Run Code Online (Sandbox Code Playgroud)