使用搜索输入字段过滤 ng-repeat 中的嵌套对象 [英] Filtering nested objects in ng-repeat with a search input field

查看:24
本文介绍了使用搜索输入字段过滤 ng-repeat 中的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用搜索文本框过滤 ng-repeat 中的嵌套对象.

I am trying to filter nested objects in ng-repeat by using a search textbox.

给定以下对象:

$scope.items = {
    "1": {
        name: "First Item",
        tag: "first"
    },
    "2": {
        name: "Second Item",
        tag: "second"
    }
};

我想做这样的事情:

<input type="text" name="serchBox" ng-model="searchByName">
<p ng-repeat="(key, values) in items | filter:{name: searchByName}">
    Using both {{key}} and {{values.name}}
</p>

这确实行不通.我尝试了很多东西,但无法使其正常工作.我不想改变我的对象.我搜索了很多,但没有找到适合我需要的东西.

This is indeed not working. I tried a lot of things and I couldn't make it work properly. I don't want to change my object. I was searching a lot but I didn't find anything that fits my needings.

推荐答案

我终于找到了自己问题的答案.

I've finally got the answer to my own question.

我只需要创建自己的过滤器并使用正则表达式检查对象内的属性是否具有所需的值:

I only had to create my own filter and check if the properties inside the object have the desired value by using regular expressions:

app.filter('customSearchFilter', function() {
return function(input, term) {
    var regex = new RegExp(term || '', 'i');
    var obj = {};
    angular.forEach(input, function(v, i){
      if(regex.test(v.name + '')){
        obj[i]=v;
      }
    });
    return obj;
  };
});

并以这种方式在 HTML 中应用它:

And apply it in the HTML this way:

<input type="text" ng-model="searchName" />
<ul>      
  <li ng-repeat="(key, val) in items | customSearchFilter:searchName">Both {{key}} and {{val.name}}</li>
</ul>

我创建了这个 Plunker 来展示我的解决方案

I created this Plunker to show my solution in action

这篇关于使用搜索输入字段过滤 ng-repeat 中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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