在angularjs中使用通配符过滤器

时间:2014-08-18 10:24:37

标签: javascript regex angularjs

我尝试使用通配符过滤值列表。

searchString = "ab*cd"

应该返回以" ab"开头的所有值。并以" cd"结束。

到目前为止,我已尝试将字符串拆分为星号所在的多个子字符串,然后搜索以第一个子字符串开头的所有单词,并同时以第二个字符串结尾(或两个中的一个,取决于星号的位置。)

我问是否有更好的方法可以做到这一点。

这是搜索以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);
};

1 个答案:

答案 0 :(得分:4)

编写自定义过滤器,如:

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;
  };
});

过滤器应该是:

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

HTML示例

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

演示 Plunker

相关问题