0

I want to filter a list of elements by regex (user will type a regex in the input search field) using AngularJS filter.

I wrote everything that seemed to be necessary for me, but I can't manage to make the regex work correctly.

Here is what I've done so far:

View.html

<div ng-controller="listCtrl">
<input type="text" placeholder="search by any" ng-model="search.$">
<input type="text" placeholder="search by fist name" ng-model="search.fname">
<input type="text" placeholder="search by last name" ng-model="search.lname" >
<input type="text" placeholder="search by tel" ng-model="search.tel" >
<input type="text" placeholder="search by date" ng-model="search.date">
<table>
        <tr ng-repeat="user in users|regex : search as res">
           <td>{{user.fname}}</td>
            <td>{{user.lname.toUpperCase()}}</td>
            <td>{{user.tel}}</td>
            <td>{{user.date | date: 'EEE'}}</td>
        </tr>
        <tr ng-if="res.length < 1">
            <td>No elements found...</td>
        </t>
        </table>
</div>

app.js

...
app.filter('regex', function() {

  return function(input, property) {
   var patt;
   var field;
   var out = [];
   if(input === undefined || property === undefined) {
    return out;
  }

  angular.forEach(property, function(key, value) {
   patt = new RegExp(key);   
   field = value;
 });

  for (var i = 0; i < input.length; i++){
    if(patt.test(input[i][eval(field)]))
      out.push(input[i]);
  }      
  return out;
};
});
...

The listCtrl will just add some elements to $scope.

What is wrong here?

3
  • FYI this has to be one of the slowest solutions to filter data Commented Oct 20, 2015 at 15:38
  • @Dalorzo could you give us a good solution to filter data by regex? Commented Oct 20, 2015 at 15:41
  • do you want to enter several regular expressions in each field? Commented Oct 20, 2015 at 15:44

1 Answer 1

1

You should just be able to call a function as part of your ng-repeat filter expression, ie.

then in your controller you'd have something like:

    function textRegEx(row) {
         var regex = new RegExp("row");
         return regex.test(row)
    }

This is for the entire row. You'd have to adapt it to work on just one of the fields. I posted a codepen earlier today here: http://codepen.io/anon/pen/yOjdJV?editors=1010 with a dropdown for selecting the field you could adapt. Obviously if you're enabling searching on multiple fields you could concatenate the calls to regex.test into a single line.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.