Yulian
Yulian

Reputation: 6759

How to clear the filter in a select element in Angular?

I have the following HTML:

<select ng-options="mark.id as mark.name for mark in marks" ng-model="markSearch.mark.id">
    <option value="">-- Choose mark --</option>
</select>
...
<tr ng-repeat-start="pipeType in pipeTypes | filter:markSearch">

I want to filter my pipeType objects based on the selected option for the mark. Every pipeType object has a mark object that consists of two fields - id and name. I want to be able to clear the filter when I choose the "-- Choose mark --" option. However, when I click on the "-- Choose mark --" option, none of the pipeType objects are visualized. I want to visualize all objects when this scenario occurs. What should I change in my code?

Edit: Here's a plunk.

Edit 2: I've accepted Matho's answer and it works. Just in case somebody else is wondering why it works, I guess that brief explanation (taken from a comment from this answer) will clear your thoughts.

For each element in the array Angular will call the comparator function and pass in "markSearch" as expected and the element as "actual". So we say, if the expected or "markSearch" is empty, then match ALL elements (return true). Otherwise, perform a 'strict' object comparison

Upvotes: 0

Views: 993

Answers (1)

You can implement your own comparator function.

I forked your plunk here should work just fine.

Basically you should add a parameter to the filter : expression : comparatorFnthis function should be available on your controller's scope.

Update: remember to check the angular docs for filter!

Upvotes: 2

Related Questions