本文翻译自: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. 我认为这将是一个非常普遍的事情,但我找不到如何在AngularJS中处理它。 Let's say I have a list of events and want to output them with AngularJS, then that's pretty easy: 假设我有一个事件列表并希望使用AngularJS输出它们,那么这很简单:
<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? 唯一可以接近的是带有events.length
的ng-switch
(如何在对象而不是数组时检查是否为空?),但这真的是我唯一的选择吗?
#1楼
参考:https://stackoom.com/question/pmDn/AngularJS-ng-repeat处理空列表案例
#2楼
You can use ngShow . 你可以使用ngShow 。
<li ng-show="!events.length">No events</li>
Or you can use ngHide 或者你可以使用ngHide
<li ng-hide="events.length">No events</li>
For object you can test Object.keys . 对于对象,您可以测试Object.keys 。
#3楼
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: 您可能想要检查angular-ui指令 ui-if
如果您只想在列表为空时从DOM中删除ul
:
<ul ui-if="!!events.length">
<li ng-repeat="event in events">{{event.title}}</li>
</ul>
#4楼
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>
#5楼
With the newer versions of angularjs the correct answer to this question is to use ng-if
: 使用更新版本的angularjs,这个问题的正确答案是使用ng-if
:
<ul>
<li ng-if="list.length === 0">( No items in this list yet! )</li>
<li ng-repeat="item in list">{{ item }}</li>
</ul>
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. 当列表即将下载时,此解决方案不会闪烁,因为必须定义列表并且长度为0才能显示消息。
Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview 这是一个使用它的插图: http ://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p = preview
Tip: You can also show a loading text or spinner: 提示:您还可以显示加载文本或微调器:
<li ng-if="!list">( Loading... )</li>
#6楼
<ul>
<li ng-repeat="item in items | filter:keyword as filteredItems">
...
</li>
<li ng-if="filteredItems.length===0">
No items found
</li>
</ul>
This is similar to @Konrad 'ktoso' Malawski but slightly easier to remember. 这类似于@Konrad'ktoso'Malawski,但稍微容易记住。
Tested with Angular 1.4 使用Angular 1.4进行测试