AngularJS Checkbox Filter
There are several implementations possible. Here's one:
-
Have a
$scope.filter = {}
object to hold the state of each filter. E.g.{red: true, white: false...}
. -
Associate each checkbox with the corresponding property using
ng-model
. E.g.:input type="checkbox" ng-model="filter['red']" />
. -
Have a function (e.g.
$scope.filterByCategory(wine)
) that decides if a wine should be displayed or not (based on the$scope.filter
object). -
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)
noFilter($scope.filter);
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.
keys(filterObj).
every(function (key) { return !filterObj[key]; });
}
465