Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 705
Vural Avatar asked Aug 21 '12 00:08

Vural


4 Answers

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>
like image 131
Gloopy Avatar answered Nov 19 '22 16:11

Gloopy


You can use function in filter expression. So basically, you can do any filtering possible with javascript.

<li ng-repeat="name in names | filter:myFilter"> {{ name }}

In controller:

$scope.myFilter = function(user) {
   return /^c5$/.test(user.type);
};
like image 34
Tosh Avatar answered Nov 19 '22 17:11

Tosh


Regular expressions are indeed powerful and can handle all kinds of matches including an exact match like ^c5$.

However, the body of this question reveals that the issue would be addressed by always filtering by exact matches.

You can specify that the Angular filter should use the exact match comparator by setting the 3rd argument to true:

filter:{type:'c5'}:true
like image 23
Colin Avatar answered Nov 19 '22 16:11

Colin


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.

like image 1
Iain529 Avatar answered Nov 19 '22 16:11

Iain529