Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 980
YoroDiallo Avatar asked Dec 04 '25 21:12

YoroDiallo


2 Answers

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.

like image 199
frosty Avatar answered Dec 06 '25 09:12

frosty


In your example I advise you to use a filter instead of using "ng-if", you should create a filter like:

angular.module('moduleName').filter(birdsFilter);
function birdsFilter(creature) {
    return creature.type == 'bird';
}

With the filter you can rewrite your code like this:

<div ng-hide="birds.length">
  <h1>Birds</h1>
  <ul>
    <li ng-repeat="bird in birds = (creatures | filter:birdsFilter)">{{bird.name}}</li>
  </ul>
</div>
like image 43
Rafael Teles Avatar answered Dec 06 '25 10:12

Rafael Teles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!