58

I need to filter a list of items by their category. I want the user to be able to click a button, and then have the filter applied to a list.

At the moment, I have this working to an extent.

Let's say for example I have a list of movies, rendered like so:

<li ng-repeat="movie in movieList | filter:filters">{{ movie.title }}</li>

And I also have a list of movie genres (rendered as buttons, which when clicked will filter the list of movies) rendered like so:

<li ng-repeat="genre in genres">
    <a ng-click="filters.genre = genre.name" ng-click='changeGenre(genre.name)'>{{genre.name}}</a>
</li>

(All the 'changeGenre()' function does is update the scope to show which genre is currently being viewed).

Now this works fine up until I have a situation where, say I have the 2 genres: 'Action' and 'Action Adventure'. When I filter by movies with the genre 'Action', I not only get a list of Action movies, but also Action Adventure movies.

Is there a way I can get an exact match using the filter?

David Undy
  • 943
  • 2
  • 7
  • 12

3 Answers3

137

This is now provided natively within the filter. You can just pass true to the filter to enable strict matching.

<li ng-repeat="movie in movieList | filter : filters : true">{{ movie.title }}</li>

Refereces

https://docs.angularjs.org/api/ng/filter/filter

https://stackoverflow.com/a/18243147/1466430

Community
  • 1
  • 1
ScottGuymer
  • 1,885
  • 1
  • 17
  • 22
48

In case someone wants to use the filter on the JavaScript side you can do it like:

$scope.filtered = $filter('filter')($scope.movieList, { genre.name: filters.genre}, true);

Notice the true at the end... it indicates that is to search for the exact match.

Paulo Griiettner
  • 1,115
  • 12
  • 18
8

filter can also take a function where you can implement your own filter. I made a plunker showing it in action: http://plnkr.co/edit/v0uzGS?p=preview

Here's the relevant code:

$scope.ChooseGenreFunction = function(genre) {
  $scope.filters = function(movie) {
    return movie.genre === genre;
  };
};
$scope.ChooseGenreString = function(genre) {
  $scope.filters = genre;
};
bguiz
  • 27,371
  • 47
  • 154
  • 243
John Tseng
  • 6,262
  • 2
  • 27
  • 35