Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - How to use Regex with ng-repeat in AngularJs?

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

<div ng-repeat="user in users | filter:{'type':/^c5$/}"></div>

I have users array and I only want to display the users with type c5.

If I use

filter:{'type':'c5'} 

then its displaying the users with type "ac5x" too, because its contains c5.

How can I solve this problem? Maybe there is another solution.

Thank You!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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):

<div ng-repeat="user in users | regex:'type':'^c5$'"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...