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

查看:60
本文介绍了过滤器在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.

我正在使用此搜索表:

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

朋克

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

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.

这是朋克

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

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