How to filter multiple values (OR operation) in angularJS

前端 未结 20 1269
清酒与你
清酒与你 2020-11-22 10:01

I want to use the filter in angular and want to filter for multiple values, if it has either one of the values then it should be displayed.

I have for

20条回答
  •  无人共我
    2020-11-22 10:25

    Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,

    myApp.filter('filterMultiple',['$filter',function ($filter) {
    return function (items, keyObj) {
        var filterObj = {
            data:items,
            filteredData:[],
            applyFilter : function(obj,key){
                var fData = [];
                if (this.filteredData.length == 0)
                    this.filteredData = this.data;
                if (obj){
                    var fObj = {};
                    if (!angular.isArray(obj)){
                        fObj[key] = obj;
                        fData = fData.concat($filter('filter')(this.filteredData,fObj));
                    } else if (angular.isArray(obj)){
                        if (obj.length > 0){
                            for (var i=0;i 0){
                        this.filteredData = fData;
                    }
                }
            }
        };
        if (keyObj){
            angular.forEach(keyObj,function(obj,key){
                filterObj.applyFilter(obj,key);
            });
        }
        return filterObj.filteredData;
    }
    }]);
    

    Usage:

    arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}
    

    Here is a fiddle example with implementation of above "filterMutiple" custom filter. :::Fiddle Example:::

提交回复
热议问题