YoroDiallo YoroDiallo - 3 months ago 21
AngularJS Question

Hide parent element in DOM when children are empty

<div>
<h1>Birds</h1>
<ul>
<li ng-if="bird.type === 'bird'"
ng-repeat="bird in creatures">{{bird.name}}</li>
</ul>
</div>


I have a response from the server and I want to put it into the list. But when the list is empty I need to hide this div container. For example if
bird.type === 'bird'
is not in the array - I want to hide div. But I want to use bird after ng-repeat so I cant make
ng-if="bird.type === 'bird'"
on
div
. Can I check if li is empty, then hide the div?

plunkr example

AngularJS ng-repeat handle empty list case - It's not the same. I don't want to hide li if it empty, I want to hide parent where I have h1 - when li is empty.

Answer

You could do the following:

<div ng-if="hasBirds(creatures)">
  <h1>Birds</h1>
  <ul>
    <li ng-if="bird.type === 'bird'"
        ng-repeat="bird in creatures">{{bird.name}}</li>
  </ul>
</div>

And then in controller/directive you can add the hasBirds function.

$scope.hasBirds = function(list){
    return list.filter(function(item){return item.type === 'bird'}).length > 0;
}

This hasBirds function would get called often, but would allow you to hide/show the heading of the birds exist.

Comments