如何在 AngularJs 中使用正则表达式和 ng-repeat? [英] How to use Regex with ng-repeat in AngularJs?

查看:30
本文介绍了如何在 AngularJs 中使用正则表达式和 ng-repeat?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 ng-repeat 中使用正则表达式.我已经尝试了以下代码,但它不起作用.

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>

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

I have users array and I only want to display the users with type c5.

如果我使用

filter:{'type':'c5'} 

然后它也显示类型为ac5x"的用户,因为它包含 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.

谢谢!

推荐答案

tosh 提到的应该对你有用!

What tosh mentions should work for you!

如果您发现自己想要更频繁地使用正则表达式进行过滤,您可以创建一个自定义过滤器.this fiddle 之类的东西可以让你指定一个字段来检查正则表达式:

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;
  };
});

这样使用,其中 'type' 表示您要检查的字段(在本例中为名为 type 的字段):

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>

这篇关于如何在 AngularJs 中使用正则表达式和 ng-repeat?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆