Search code examples
jqueryangularjsangular-filters

Reset a custom angular filter when reset button is clicked


I have made a custom Angular filter with checkboxes and the search results change depending on the selected checkboxes. I am creating a reset button that will reset all my filters and I cannot seem to figure what to do. I know I need to add more things under resetFilters function but the codes I tried aren't working. Please help!

JS portion:

 $scope.FREEcheckChange = function(){
        for (var check4 in $scope.FREE){
            if($scope.FREE[check4].on){
                $scope.showAll4 = false;
                return;                
            }
        }
        $scope.showAll4 = true;
    }; //end of FREEcheckChange


  $scope.FREEFilter = function(f){
    if($scope.showAll4) 
        {return true;}
    var selectedBox4 = false;

    for(var i in  $scope.FREE){         
        var catFive =  $scope.FREE[i];
        if(catFive.on){
            if(f.cat.indexOf(catFive.name) == -1) {return false;}
            else {selectedBox4 = true;}
        }             
    }         

    return selectedBox4;        
}


$scope.YEARFilter = function(d){
    if($scope.showAll3) 
        {return true;}
    var selectedBox3 = false;

    for(var i in  $scope.YEAR){         
        var catFour =  $scope.YEAR[i];
        // console.log(catFour); 
        if(catFour.on){
            if(d.cat.indexOf(catFour.name) == -1) {return false;}
            else {selectedBox3 = true;}
        }             
    }         
    return selectedBox3;        
}
 $scope.resetFilters = function(){
        $('input:checkbox').removeAttr('checked'); }

HTML:

 <div ng-repeat="item in filteredProducts = ( products | filter: YEARFilter |  filter: FREEFilter | searchFilter:searchString )">

<button type="button" class="btn btn-default btn-block" style="margin: 7px 0;" ng-click="resetFilters();">RESET FILTERS</button>

<div ng-repeat= "FREEcategory in FREE">
                        <input type="checkbox" ng-model="FREEcategory.on" ng-change ="FREEcheckChange()">           
                        {{FREEcategory.name}}
                    </div>
 <div  ng-repeat= "YEARcategory in YEAR">
                    <input type="checkbox" ng-model="YEARcategory.on" ng-change ="YEARcheckChange()">           
                    {{YEARcategory.name}}
                    </div>

Solution

  • Like @charlietfl said in the comments, update the model and not the checkboxes using jQuery. For example something like this (not tested):

    $scope.resetFilters = function(){
        angular.forEach($scope.FREE, function(value, key) {
            $scope.FREE[key].on = false;
        });
        angular.forEach($scope.YEAR, function(value, key) {
            $scope.YEAR[key].on = false;
        });
    }