Search code examples
javascriptangularjsangular-filters

Angular filtering by friend.brand.id inside of friends works, but can't use the || undefined trick to reset the filter when NULL


So it's the year 2075 and immortal humans enslaved mortal humans. There is a store that sells mortal friends and is trying to build the app so that customers can manage their friends by filtering through them using their favorite brand. But apparently angular.js is broken.

<select ng-model="searchText2.id" ng-options="friend.brand.id as friend.name for friend in friends">
  <option value="">Select</option>
</select>

  <tr ng-repeat="friend in friends | filter:{brand:searchText2 || undefined}">

I get a nice filtering going on here don't get me wrong, but the UX manager will feed me to the cyber-albino-ligers if the filter doesn't reset when I click select.

HERE IS THE PLUNKER ---> http://plnkr.co/edit/1MPc0BqQGPNIJZ9FRR6z?p=preview


Solution

  • I've updated the plunker with a possible solution.

    Within the filter you could use a ternary statement to do what you intend.

    <tr ng-repeat="friend in friends | filter:{ brand:(searchText2.id === null) ? {id: undefined}: searchText2}">
    

    When you select the default option of "Select a name" angular will set the value to null but you want to pass in an undefined to clear the filter.

    Hope that helps you out on your quest!