Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS checkbox filter

I would like to filter the results.

There is a list of wines, my wish is when no checkbox is checked, the entire list of wine is displayed.

  • when only 1 checkbox is checked is displayed the related category
  • when more than one checkbox are checked the related categories are displayed

I'm a newbie to AngularJS, I tried with ng-model wihout success, here is the code without ng-model associated to the function:

<html ng-app="exampleApp">
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.10/angular.min.js"></script>

    <script>
        angular.module("exampleApp", [])
                .controller("defaultCtrl", function ($scope) {
                    $scope.wines = [
                        { name: "Wine A", category: "red" },
                        { name: "Wine B", category: "red" },
                        { name: "wine C", category: "white" },
                        { name: "Wine D", category: "red" },
                        { name: "Wine E", category: "red" },
                        { name: "wine F", category: "white" },
                        { name: "wine G", category: "champagne"},
                        { name: "wine H", category: "champagne" }

                    ];


                    $scope.selectItems = function (item) {
                        return item.category == "red";
                    };

                    $scope.selectItems = function (item) {
                        return item.category == "white";
                    };

                    $scope.selectItems = function (item) {
                        return item.category == "champagne";
                    };
                });
    </script>
</head>
<body ng-controller="defaultCtrl">

<h4>red: <input type="checkbox"></h4>
<h4>white: <input type="checkbox"></h4>
<h4>champagne: <input type="checkbox"></h4>



            <div ng-repeat="w in wines | filter:selectItems">
                {{w.name}}
                {{w.category}}
            </div>


</body>
</html>

How to use ng-model or ng-change to associate a function to each checkbox button to have a real time filtering model??

like image 401
Stéphane Avatar asked Jun 01 '14 18:06

Stéphane


People also ask

What is a checkbox in AngularJS?

In angularjs checkboxes are the form controls which are used to handle multiple selections in a form. Generally checkboxes will return true or false based on selection status.

How to bind array list data to checkboxes in AngularJS?

Following is the result of using checkboxes in angularjs applications. By using ng-repeat directive in angularjs we can bind array list values to checkboxes. Following is the example of binding array list data to checkboxes in angularjs applications.

What are filters in AngularJS?

Filters can be added in AngularJS to format data. AngularJS provides filters to transform data: currency Format a number to a currency format. date Format a date to a specified format. filter Select a subset of items from an array.

What is filtering with checkboxes?

The idea of filtering with checkboxes means that you have discrete values associated with the checkboxes, when checked, and you want to compare those checked values against properties within an array of objects. Sounds straight-forward, right? The first hurdle is handling checkboxes in Angular.


2 Answers

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)
      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]; });
}

See, also, this short demo.


UPDATE:

I created a modified version, which supports multiple filters (not just filtering by category).
Basically, it dynamically detects the available properties (based on the first wine element), adds controls (groups of check-boxes) for applying filters based on each property and features a custom filter function that:

  1. Filters each wine item, based on every property.
  2. If a property has no filter applied (i.e. no check-box checked), it is ignored.
  3. If a property has check-boxes checked, it is used for filtering out wine items (see above).
  4. There is code for applying multiple filters using AND (i.e. all properties must match) or OR (at least one property must match).

See, also, this updated demo.

like image 74
gkalpak Avatar answered Sep 20 '22 18:09

gkalpak


Just to add onto @gkalpak answer, I found this codepen which allows you to provide the total amount left after an option is selected for each category.

Change the ng-repeat from:

<div ng-repeat="wine in (ctrl.wines | filter:ctrl.filterByProperties) as filteredWines">
      {{ wine.name }} <i>({{ wine.category }})</i>
</div>

To

<div ng-repeat="wine in filtered = (ctrl.wines | filter:ctrl.filterByProperties) as filteredWines">
  {{ wine.name }} <i>({{ wine.category }})</i>
</div>

And with the input labels add:

<label>
    <input type="checkbox" ng-model="ctrl.filter[prop][value]" />
    {{ value }}({{(filtered | filter:value:true).length}})
</label>
like image 42
Patrick McDermott Avatar answered Sep 18 '22 18:09

Patrick McDermott