如何在AngularJs中使用带有ng-repeat的正则表达式?

Vur*_*ral 18 javascript regex frameworks angularjs

我想在ng-repeat中使用正则表达式.我尝试了以下代码,但它无法正常工作.

<div ng-repeat="user in users | filter:{'type':/^c5$/}"></div>
Run Code Online (Sandbox Code Playgroud)

我有用户数组,我只想显示类型为c5的用户.

如果我使用

filter:{'type':'c5'} 
Run Code Online (Sandbox Code Playgroud)

然后它也显示类型为"ac5x"的用户,因为它包含c5.

我怎么解决这个问题?也许有另一种解决方案.

谢谢!

Glo*_*opy 36

提到的应该对你有用!

如果您发现自己希望更频繁地使用正则表达式进行过滤,则可以创建自定义过滤器.像这个小提琴这样的东西会让你指定一个字段来检查正则表达式:

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;
  };
});
Run Code Online (Sandbox Code Playgroud)

像这样使用,'type'表示你要检查的字段(在这种情况下是一个名为type的字段):

<div ng-repeat="user in users | regex:'type':'^c5$'"></div>
Run Code Online (Sandbox Code Playgroud)


Tos*_*osh 16

您可以在过滤器表达式中使用函数.基本上,你可以使用javascript进行任何过滤.

<li ng-repeat="name in names | filter:myFilter"> {{ name }}
Run Code Online (Sandbox Code Playgroud)

在控制器中:

$scope.myFilter = function(user) {
   return /^c5$/.test(user.type);
};
Run Code Online (Sandbox Code Playgroud)