AngularJS Checkbox Filter

There are several implementations possible. Here's one:

  1. Have a $scope.filter = {} object to hold the state of each filter. E.g. {red: true, white: false...}.

  2. Associate each checkbox with the corresponding property using ng-model. E.g.: input type="checkbox" ng-model="filter['red']" />.

  3. Have a function (e.g. $scope.filterByCategory(wine)) that decides if a wine should be displayed or not (based on the $scope.filter object).

  4. Use that function to filter the items based on their category. E.g. <div ng-repeat="wine in wines | filter:filterByCategory">


The filterByCategory function could be implemented like this:

function filterByCategory(wine) {
  // Display the wine if
  var displayWine =
      // the wine's category checkbox is checked (`filter[category]` is true)
      $scope.filter[wine.category] ||   // or 

      // no checkbox is checked (all `filter[...]` are false)

  return displayWine;

where noFilter() is a function that checks if there is any filter activated (and returns true if there is none):

function noFilter(filterObj) {
  return Object.
    every(function (key) { return !filterObj[key]; });