StrugglingCoder
StrugglingCoder

Reputation: 5021

Passing arguments to angularjs custom filters

I have a global filter that filters data based on a text input.

<search-box ng-model="vm.filter.keyword"></search-box>

And, we use the filter like this

<tr ng-repeat="group in vm.groups | searchGlobal:vm.filter.keyword

My filter looks like:

.filter('searchGlobal',
    function searchGlobal () {
        return function searchGlobal (searchValArr,filterText) {
            var filteredData = [];
            for(var i = 0; i <searchValArr.length; i++) {
                if (searchValArr[i].name.toLowerCase().indexOf(filterText.toLowerCase()) !== -1 || 
                searchValArr[i].id.indexOf(filterText) !== -1) {
                    filteredData.push(searchValArr[i]);
                }                        
            }
            return filteredData;
        };
    });

Now, this is the problem.

The fields to look for might just not be name and id.

In some cases they might be name, phone_numbers,

in some case name,age,refNumbers.

How do I handle the scenario logic inside the filter accordingly?

Upvotes: 0

Views: 75

Answers (2)

Razzildinho
Razzildinho

Reputation: 2584

You can create a filter that will check if any of the object keys contains the keyword.

I have created a simple example here.

The filter function looks like the following, note that it uses some modern JS features like Object.values and String.includes which can be exchanged if older browser support is required.

angular.module("myApp")
  .filter("searchGlobal", function(){
    return function(data, keyword){
      // Return a filtered array of items in the initial array
      return data.filter(function(obj){
        // Check if any (some) of the object keys contains the keyword
        return Object.values(obj).some(function(value){
          return value.includes(keyword);
        });
      });
    };
  });

Upvotes: 0

Tan Duong
Tan Duong

Reputation: 2142

You can add one more param for checking the property you want

<tr ng-repeat="group in vm.groups | searchGlobal:vm.filter.keyword:vm.filter.listKeys

.filter('searchGlobal',
function searchGlobal () {
    return function searchGlobal (searchValArr,filterText, listKeys) {
        var filteredData = [];
        var listIdAdd = [];

        if (angular.isUnDefined(listKeys) || !angular.isArray(listKeys)) {
            listKeys = ['name', 'id'];
        }
        for(var i = 0; i <searchValArr.length; i++) {
            for (var j = 0; j < listKeys.length; j++) {
                if (searchValArr[i][listKeys[j]].toLowerCase().indexOf(filterText.toLowerCase()) !== -1 &&
                    listIdAdd.indexOf(searchValArr[i].id === -1)) {
                    filteredData.push(searchValArr[i]);
                    listIdAdd.push(searchValArr[i].id);
                }
            }
        }
        return filteredData;
    };
});

Hope this help

Upvotes: 1

Related Questions