如何在 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>
相关文章