Search code examples
angularjschecklist-model

Select all elements when all checkboxes unchecked


I am working on a webpage that would display a list of products with several attributes (color, size, style). I would need that when all checkboxes are unchecked, the page would show all the products, and just when I start checking one the categories will it start filtering the products. Is that possible with checklist-model? Thanks in advance


Solution

  • Yes you can use checklist-model (http://vitalets.github.io/checklist-model/ if you are refreeing this) Have the code below which will tell you how can you do it just add the filtering logic to it.

    Controller code

    myApp.controller('MyCtrl', function ($scope) {
    //On controller load show all the products
    $scope.filters = ['color','style','size'];
    $scope.allproducts = [];
    $scope.selectedFilters = {
        filters: []
    };
    
    $scope.applyFilter = function (filters)
    {
        //Add filtering logic to filter objects from allproducts 
        //according to filter values in the filters array passed in the function.
        //the data will be changed in if filter applied to allproducts array as allproducts in binded in view.
    
    }
    
    
    $scope.$watchCollection('$scope.selectedFilters.filters', function (newVal, oldVal) {
        //If all values are unchecked
        if($scope.selectedFilters.filters.length == 0)
        {
            //Show All products
        }
        else {
            //Show the filtered products
            applyFilter($scope.selectedFilters.filters) ;   
           } 
    }); });
    

    View code:

        <div ng-app="MyApp" ng-controller="MyCtrl">
        <label ng-repeat="filter in filters">
            <input type="checkbox" checklist-model="selectedFilters.filters" checklist-value="filter"> {{filter}}
        </label>
        <label ng-repeat="product in allproducts">{{product}}</label> 
    </div>