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?
With the newer versions of angularjs the correct answer to this question is to use
ng-if
:This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.
Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview
Tip: You can also show a loading text or spinner:
Here's a different approach using CSS instead of JavaScript/AngularJS.
CSS:
Markup:
If the list is empty, <li ng-repeat="item in filteredItems">, etc. will get commented out and will become a comment instead of a li element.
i usually use ng-show
where variable you define for example