How to filter a select with ng-options in Angular?

Vivian River picture Vivian River · Oct 22, 2015 · Viewed 68.8k times · Source

I've written the following proof-of-concept of an Angular app that allows a person to vote for President of the US.

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

My voting app displays a list of the candidates names along with a profile for each candidate, which in this case, consists of the candidate's name and gender.

For the purpose of this question, please pretend that the roster of candidates to choose from is fetched from a remote data source, but will follow the same format as the example.

Suppose that shortly before the election is to be held, a constitutional amendment is passed mandating that the next US President must be female. Suppose that the data source cannot be updated in time for the election, and the boss said to me, "I've heard that with Angular, you can arbitrarily choose which items from the data source appear on the form using a filter. Make it happen!"

Following along with some examples I've seen on-line, I've written the above code, but it no longer displays any candidate. What did I do wrong?

How can I filter the options in a select list using an Angular filter?

Answer

Benoit Charpi&#233;-Pruvost picture Benoit Charpié-Pruvost · Oct 22, 2015

You just forgot ":" after filter keyword.

<select 
    ng-model="ctrl.selection"
    ng-options="person as person.name for person in ctrl.candidates | filter:{gender:'female'}">
</select>