nehalist nehalist - 5 months ago 20
AngularJS Question

Hide group on filter in Angular

My REST API is returning grouped data,

{
"Homer Simpson": [
{
"name": "First article",
"type": "text"
},
{
"name": "Second article",
"type": "text"
}
],
"Marge Simpson": [
{
"name": "Third article"
"type": "text
}
]
}


Articles can be filtered:

<input type="text" placeholder="Quicksearch" ng-model="quicksearch">
...
<div class="article-group" ng-repeat="(author, articles) in articles">
<h3>{{author}} ({{filtered.length}})</h3>
<div class="article" ng-repeat="article in articles | filter: { name: quicksearch } as filtered">


The important thing here is the
({{filtered.length}})
. After applying a filter by typing something into the quicksearch input the length changes. Everything works fine, but I'd like hide "empty" authors; if you type in "third" you should no longer see Homer Simpson.

Tried
ng-if="filtered.length > 0"
on the
article-group
div, but that doesn't work.

Answer

You can simply put ng-show="filtered.length" on .article-group container:

<div class="article-group" ng-show="filtered.length" ng-repeat="(author, articles) in articles">
  <h3>{{author}} ({{filtered.length}})</h3>
  <div class="article" ng-repeat="article in articles | filter: { name: quicksearch } as filtered">
    <pre>{{ article | json }}</pre>
  </div>
</div>
Comments