angular js multiple checkbox with custom filters

我的未来我决定 提交于 2019-12-04 16:06:30

Here is the OR case filter. It will return results for items that match the merchant OR brand.

Example: http://jsfiddle.net/TheSharpieOne/ZebC7/

What was added:

We needed something to store the checkboxes checked, it will be an object, the key being the merchant or brand and the value being true/false if it is selected. Then we look through the objects to determine what is selected and do whatever you want in the searchFilter method, which is passed to the repeat's filter.

<label><input type="checkbox" ng-model="merchantCheckboxes[Merchant.Merchantname]" /> {{Merchant.Merchantname}}</label>

Here is the additions to the control"

$scope.merchantCheckboxes = {};
$scope.brandCheckboxes = {};
function getChecked(obj){
    var checked = [];
    for(var key in obj) if(obj[key]) checked.push(key);
    return checked;
}
$scope.searchFilter = function(row){
    var mercChecked = getChecked($scope.merchantCheckboxes);
    var brandChecked = getChecked($scope.brandCheckboxes);
    if(mercChecked.length == 0 && brandChecked.length == 0)
        return true;
    else{
        if($scope.merchantCheckboxes[row.MerchantName])
            return true;
        else{
            return row.BrandList.split(/,\s*/).some(function(brand){
                return $scope.brandCheckboxes[brand];
            });
        }
    }
};

UPDATE

Made the checked checkboxes appear first, and changed the search filter to "AND"

Example: http://jsfiddle.net/TheSharpieOne/ZebC7/1/

<li ng-repeat="Merchant in MerchantList| orderBy:[orderChecked,'Merchantname']">

Function to order the checked ones first (made one function for both)

$scope.orderChecked = function(item){
    if(item.Merchantname && $scope.merchantCheckboxes[item.Merchantname])
        return 0;
    else if(item.brandname && item.brandname.split(/,\s*/).some(function(brand){
                return $scope.brandCheckboxes[brand];
            }))
        return 0;
    else
        return 1;
};

Also, change the search filter to "AND"

$scope.searchFilter = function(row){
    var mercChecked = getChecked($scope.merchantCheckboxes);
    var brandChecked = getChecked($scope.brandCheckboxes);
    if(mercChecked.length == 0 && brandChecked.length == 0)
        return true;
    else{
        if(($scope.merchantCheckboxes[row.MerchantName] && brandChecked.length==0)
          || (mercChecked.length == 0 && row.BrandList.split(/,\s*/).some(function(brand){
                return $scope.brandCheckboxes[brand];
            }))
          || ($scope.merchantCheckboxes[row.MerchantName] && row.BrandList.split(/,\s*/).some(function(brand){
                return $scope.brandCheckboxes[brand];
            })))
            return true;
        else{
            return false;
        }
    }
};

Some cleanup is needed, but you can see how it all can be done.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!