Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular JS, when using a select with ng-options for a filter. How do I create an "all" option?

Tags:

angularjs

I have the following data in my controller:

$scope.breeds = ["Poodle", "Collie", "German shepherd"];

$scope.dogs = [
        { name: "Bingo", breed: "Poodle" },
        { name: "Lassie", breed: "Collie" },
        { name: "Bert", breed: "German shepherd" },
        { name: "Lily", breed: "Poodle" },
        { name: "Obi-Wan", breed: "Collie" }
    ];

And here's my html:

<select ng-model="query.breed" ng-options="breed for breed in breeds">                                    
    <option value="">All breeds</option>
 </select>

   <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Breed</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="dog in dogs |filter:query">
                <td>{{dog.name}}</td>
                <td>{{dog.breed}}</td>
            </tr>
        </tbody>
    </table>

All works fine - When I select Collie, the objects with breed == "Collie" are displayed, etc. But I can't figure out how to make the "All breeds" options work.

like image 395
Thea Avatar asked Oct 04 '13 09:10

Thea


1 Answers

When using ngOptions, value="" sets model to null which is incompatible with filter. You can use just ngRepeat.

<select ng-model="query.breed">
    <option value="">All breeds</option>
    <option ng-repeat="breed in breeds" value="{{breed}}">{{breed}}</option>
</select>
like image 58
lort Avatar answered Sep 18 '22 08:09

lort