How to use Regex with ng-repeat in AngularJs?

前端 未结 5 1308
栀梦
栀梦 2020-12-14 08:58

I want to use regex in ng-repeat. I have tried the following code but its not working.

<
5条回答
  •  心在旅途
    2020-12-14 09:37

    What tosh mentions should work for you!

    If you find yourself wanting to filter by regex more often you can create a custom filter. Something like this fiddle will let you specify a field to check against a regex:

    var myApp = angular.module('myApp', []);
    myApp.filter('regex', function() {
      return function(input, field, regex) {
          var patt = new RegExp(regex);      
          var out = [];
          for (var i = 0; i < input.length; i++){
              if(patt.test(input[i][field]))
                  out.push(input[i]);
          }      
        return out;
      };
    });
    

    Used like this where 'type' indicates the field you are checking against (in this case a field named type):

提交回复
热议问题