How to use Regex with ng-repeat in AngularJs?

前端 未结 5 1290
栀梦
栀梦 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:52

    Gloopy's answer is spot on. I implemented it in my site but I was getting an error,

    'input' is undefined

    This occurred because I was sometimes looping over nothing. I fixed this by adding a conditional to return the empty out array if input was undefined.

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

    Hopefully this will help someone who might be having the same problem

提交回复
热议问题