Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : Filter sub-content in ng-repeat

Here's a sample JSON code:

 $scope.info = [{"name":"Category1", "data":[{"name":"Item1"}, {"name":"Item2"}]},
                    {"name":"Category2", "data":[{"name":"Item3"}, {"name":"Item4"}]}];

I'm putting it in a list thanks to ng-repeat and I filter with a search box, I also order the results by categories :

<div ng-repeat="Cat in info">
      <h3>{{Cat.name}}</h3>
      <ul>
          <li ng-repeat="Item in Cat.data | filter:search" >
               {{Item.name}}
          </li>
      </ul>
</div>

The problem is: when I search, for example "Item3", it shows the Item3 in Category2 but there's still "Category1" even if there's nothing below because categories are not filtered, only their content is.

So how can I say to AngularJS: "If category1's filtered content is empty, do not show it" ?

like image 902
user3491456 Avatar asked Sep 23 '26 00:09

user3491456


1 Answers

Assign the output of the filter to a variable, and then hide the header based on the length of that.

<div ng-repeat="Cat in info" ng-hide="filtered.length == 0">
  <h3>{{Cat.name}}</h3>
  <ul>
      <li ng-repeat="Item in filtered = (Cat.data | filter:search)" >
           {{Item.name}}
      </li>
  </ul>
</div>
like image 125
Tim B Avatar answered Sep 24 '26 14:09

Tim B