Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  176] [ 5]  / answers: 1 / hits: 27335  / 12 Years ago, tue, august 21, 2012, 12:00:00

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!


More From » regex

 Answers
296

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>

[#83522] Sunday, August 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melindab

Total Points: 511
Total Questions: 109
Total Answers: 106

Location: San Marino
Member since Thu, Jun 25, 2020
4 Years ago
;