javascriptangularjsangularjs-ng-repeatangularjs-ng-show

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?


Solution

  • 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.