Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-repeat handle empty list case

I thought this would be a very common thing, but I couldn't find how to handle it in AngularJS. Let's say I have a list of events and want to output them with AngularJS, then that's pretty easy:

<ul>
    <li ng-repeat="event in events">{{event.title}}</li>
</ul>

But how do I handle the case when the list is empty? I want to have a message box in place where the list is with something like "No events" or similar. The only thing that would come close is the ng-switch with events.length (how do I check if empty when an object and not an array?), but is that really the only option I have?

like image 931
Prinzhorn Avatar asked Sep 09 '12 14:09

Prinzhorn


3 Answers

You can use ngShow.

<li ng-show="!events.length">No events</li>

See example.

Or you can use ngHide

<li ng-hide="events.length">No events</li>

See example.

For object you can test Object.keys.

like image 71
Artem Andreev Avatar answered Oct 11 '22 12:10

Artem Andreev


And if you want to use this with a filtered list here's a neat trick:

<ul>
    <li ng-repeat="item in filteredItems  = (items | filter:keyword)">
        ...
    </li>
</ul>
<div ng-hide="filteredItems.length">No items found</div>
like image 26
Konrad 'ktoso' Malawski Avatar answered Oct 11 '22 10:10

Konrad 'ktoso' Malawski


You might want to check out the angular-ui directive ui-if if you just want to remove the ul from the DOM when the list is empty:

<ul ui-if="!!events.length">
    <li ng-repeat="event in events">{{event.title}}</li>
</ul>
like image 34
Mortimer Avatar answered Oct 11 '22 12:10

Mortimer