Jose Jose - 4 months ago 26
AngularJS Question

Clear value from select element when filtering in Angular

I have a basic select element with options that dropdown hooked up to a small set of data which is being filtered using the dropdown. Initially on page load the select element has a value of

undefined
(according to the console), however after selecting any option it takes on the value of that option.

How can I go back to
undefined
? Basically I want to be able to select an option in the list that will go back to displaying all of the data. Below is my app on JSBin:

App

Answer

add a custom filter function

$scope.filterByGenre = function(item){

  if (!$scope.selectedGenre || $scope.selectedGenre == 'All'){
    return true;
  }

  return item.genre && item.genre.indexOf($scope.selectedGenre) != -1;

}

change your <select> to this:

<select ng-model="selectedGenre"
            ng-options="choice as choice for (idx, choice) in genres"
            name="genre"
            class="genre-dropdown">
</select>

change <tr ng-repeat="... filters to this:

<tr ng-repeat="movie in movies | filter:searchBar | filter:filterByGenre | orderBy:sortType:sortReverse">

Online Demo - http://jsbin.com/riyafupexu/1/edit?html,js,output

Comments