Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filters with wildcards in angularjs

I'm trying to filter a list of values with wildcards.

searchString = "ab*cd"

Should return all the values that start with "ab" and end with "cd".

So far I've tried to split the string in multiple substrings where the asterisk is and then search all the word that starts with the first substring and simultaneously end with the second one (or one of the two, depending on the position of the asterisk).

I'm asking if there is a better method of doing this.

This is the code to search strings that start with a searchString:

function escapeRegExp(string){
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
}

$scope.query = '';
var regex;
$scope.$watch('query', function (value) {
regex = new RegExp('\\b' + escapeRegExp(value), 'i');
}

$scope.filterBySearch = function(article) {
if (!$scope.query) return true;
return regex.test(article.title);
};
like image 245
Sortee Avatar asked Aug 18 '14 10:08

Sortee


Video Answer


1 Answers

Write custom filter like:

iApp.filter('myfilter', function() {
   return function( items, types) {
    var filtered = [];

    angular.forEach(items, function(item) {
       if(types.wildcard == false || item.name.match(types.value)) {
          filtered.push(item);
        }

    });

    return filtered;
  };
});

where filter should be:

$scope.types = {wildcard:false, value: /^ab.*cd$/};

HTML example

  <tr data-ng-repeat="value in values |  myfilter:types">

Demo Plunker

like image 194
Maxim Shoustin Avatar answered Sep 18 '22 21:09

Maxim Shoustin