0
votes

I've been looking for severeal days how to create a dynamic filter with multiple checkboxes in AngularJS easily and none of the solutions I found satisfied me.

Here is an example of a filter that will display everything when the checkboxes are unchecked and filter the data when checkboxes are checked. (Good for search engine to look for a hotel with wifi, balcony... for example)

Filter :

app.filter('conveniences_filter', function() {
    return function( items, types) {
        var filtered = [];
        var displayItem;
        angular.forEach(items, function(item) {
            displayItem = true;
            angular.forEach(types, function(type, key) {         
                if(type == true && item[key] == false) {
                   displayItem = false;
                }
            });
            if(displayItem == true) {
                filtered.push(item);   
            }
        });
        return filtered;
    };
});

In your controller :

    $scope.types = {wifi: false, balcony: false}

In your HTML

ng-repeat="property in properties | conveniences_filter:types"

Important : Your keys in your $scope.types have to be the same as your key in your properties items or it's not gonna work.

Example of a property here :

Object { name: property, wifi: false, balcony: true }

I hope it's gonna be useful :)

1

1 Answers

0
votes

I think it's not 100% clear what your requirements are here. At least from what I get from the code you've written is that you'd like to filter a list of objects based on their property values and that you use a "schema" object that is used to compare against the objects.

To fill the gaps in the requirements I'm assuming you want to validate against an "schema" object that contains properties that also need to match in your items. I'm also assuming that if a property is not in the "schema" object then it will not be relevant for the comparison. Also I assumed that you want all present properties in the "schema" to be valid / matching otherwise the item is not considered.

I've put together a small example solving the above requirements. In general you should use the array extra functions that come with ECMA5.1 and make things much simpler and functional style.

Example: http://jsbin.com/velobi/1/edit

Cheers Gion