<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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With