Search code examples
javascriptangularjscheckboxangular-filters

Boolean filter with checkbox on AngularJS


I have an array of objects with property published which can be true or false. I'm building a filter to be able to display only published or only not published items.

So far the published one works fine like this:

<input 
   type="checkbox" 
   ng-model="search.published" 
   ng-change="search.published = search.published ? true : undefined"> 
Published

And in the ng-repeat it looks like this:

ng-repeat="exhibitor in filterItems = (data | filter: search)"

The problem comes when I try to add another checkbox to display only unpublished items.

I've tried this with a second checkbox:

<input 
   type="checkbox" 
   ng-model="search.published" 
   ng-change="search.published = search.published ? false : undefined"> 
Unpublished

But of course it can't have the same model as the published items one. Also, the checkbox won't get ticked even if I remove the first checkbox.

Any tips on how to work around this?


Solution

  • Checkboxes automatically assign a true or false value to their ng-model values, so it is unnecessary to use ng-change the way you are.

    <input 
       type="checkbox" 
       ng-model="search.published">
    Published
    

    When checked, search.published will be true. When unchecked, it will be false. Same goes for the second checkbox, but you should use a different ng-model property.

    <input 
       type="checkbox" 
       ng-model="search.unpublished"> 
    Unpublished
    

    Next you will need to create a custom filter in your controller:

    $scope.myCustomFilter = function(exhibitor) {
        if (exhibitor.published && exhibitor.published === $scope.search.published) {
            return exhibitor;
        } else if (!exhibitor.published && exhibitor.published === $scope.search.unpublished) {
            return exhibitor;
        }
    };
    

    You will need you make sure you define $scope.search in your controller.

    $scope.search = {
        published: false,
        unpublished: false
    };
    

    Now for your ng-repeat:

    ng-repeat="exhibitor in filterItems | filter:myCustomFilter"