Filtering nested objects in ng-repeat with a search input field

梦想的初衷 提交于 2019-11-28 11:34:12

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

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>

I created this Plunker to show my solution in action

If you don't need to reuse your filter anywhere else, you can write your filtering function in controller.

scope.customSearchFilter = function(term){
    return function(item) {
        var regex = new RegExp(term || '', 'i');
        return regex.test(item.name + '');
    };
};

Filter argument is a single item, not an array.

Here is examples. 1st variant is with model, and 2nd with plain scope:

https://plnkr.co/edit/ELH8S5GymG8cHfOJqD9G

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!