过滤器在 AngularJS 中是如何工作的? [英] How does filter work in AngularJS?

查看:21
本文介绍了过滤器在 AngularJS 中是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 ng-repeat 生成的表(来自对象的数组).

I have a table generated with ng-repeat (from an objects' array).

我想用搜索文本字段过滤它.

I would like to filter it with a search text field.

我的数组中包含的对象具有深层属性.

Objects contained in my array has got deep properties.

我不知道为什么以及如何,但过滤器只对电子邮件字段起作用,该字段与其他属性一样深.

I don't know why and how, but the filter is only working on email field, which is as deep as other properties.

我正在使用这个搜索表单:

I'm using this search form :

<input type="text" name="search" ng-model="searchText" />
...
<tr ng-repeat="x in obj | filter:searchText track by $index">
  ...
</tr>

plunker

这个答案 帮助我理解为什么它不起作用.有人知道如何绕过过滤器中的 $ 验证吗?

This answer helps me to understand why it's not working. Someone knows how I can bypass the $ verification in filter ?

我使用 $ 是因为我遵循 Google Contact API 格式.

I'm using $ because I'm following the Google Contact API format.

推荐答案

email 有效,因为嵌套属性 address 不包含任何 $字符.

email works because nested property address doesn't contain any $ char.

不幸的是,我认为没有办法绕过这种行为,但是您可以制作自己的过滤器并在 ng-repeat 中使用它.

Unfortunately, I don't think there is a way to bypass this behavior, however you can make your own filter and use it in ng-repeat.

这是一个应该适合您的简单示例:

This is simple example that should work for you:

JS

app.filter('customFilter', function() {
  return function(items, keyword) {
    if (!keyword || keyword.length === 0) return items;

    return items.filter(function(item){
      var phrase = keyword.$.toLowerCase();
      return item.gd$name.gd$fullName.$t.toLowerCase().includes(phrase) || 
        item.gd$name.gd$familyName.$t.toLowerCase().includes(phrase) || 
        item.gd$name.gd$givenName.$t.toLowerCase().includes(phrase) ||
        item.gd$email[0].address.toLowerCase().includes(phrase) ||
        item.gd$phoneNumber[0].$t.toLowerCase().includes(phrase) ||
        (!!item.gd$organization[0].gd$orgTitle && item.gd$organization[0].gd$orgTitle.$t.toLowerCase().includes(phrase)) ||
        (!!item.gd$organization[0].gd$orgName && item.gd$organization[0].gd$orgName.$t.toLowerCase().includes(phrase));
    });
  }
});

HTML

<tr ng-repeat="x in obj | customFilter:searchText">

当然,您必须为可能的 null 值添加更多检查.我只是想让它处理您提供的数据.

Of course, you will have to add more checks for possible null values. I've just wanted to make it work on the data you've provided.

希望你会发现它很有用.

Hope, you'll find it useful.

这里是 plunk

这篇关于过滤器在 AngularJS 中是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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