How to use Regex with ng-repeat in AngularJs?

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

    Thanks for the regex filter idea but the previous solutions do not work for a general case, like a object case where is a multi level fields.

    For example:

    My solution is:

    .filter('regex', function() {
      return function(input, field, regex) {
        var f, fields, i, j, out, patt;
        if (input != null) {
          patt = new RegExp(regex);
          i = 0;
          out = [];
          while (i < input.length) {
            fields = field.split('.').reverse();
            j = input[i];
            while (fields.length > 0) {
              f = fields.pop();
              j = j[f];
            }
            if (patt.test(j)) {
              out.push(input[i]);
            }
            i++;
          }
          return out;
        }
      };
    });
    

    It works for multi level objects or simple object with just one level of attributes.

    To late but hope it help you to see from different angle.

    This is the code in CoffeeScript, is cleaner:

    angular.module('yourApp')
        .filter 'regex', ->
            (input, field, regex) ->
                if input?
                    patt = new RegExp(regex)
                    i = 0
                    out = []
                    while i < input.length
                        fields = field.split('.').reverse()
                        j = input[i]
                        while fields.length > 0
                            f = fields.pop()
                            j = j[f]
                        if patt.test(j)
                            out.push input[i]
                        i++
                    return out
    

提交回复
热议问题