Javascript ng-if 检查数组是否为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35041618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-if check if array is empty
提问by TheEks
The API I am working with returns this if there are no items in the array
如果数组中没有项目,我正在使用的 API 会返回此值
items: []
If there are items in the array it returns something like
如果数组中有项目,它会返回类似
items: [
{
name: 'Bla'
}
]
In my template I believe I need to use ng-if to either show/hide an element based on whether there is data in there or not.
在我的模板中,我相信我需要使用 ng-if 根据其中是否有数据来显示/隐藏元素。
<p ng-if="post.capabilities.items"><strong>Topics</strong>: <span ng-repeat="topic in post.capabilities.items">{{topic.name}}</p>
However I could be totally off base as this is my first time working in Angular, and there may be a much better way to do what I am trying to do.
但是,我可能会完全偏离基础,因为这是我第一次在 Angular 中工作,并且可能有更好的方法来做我想做的事情。
回答by Martijn Welker
post.capabilities.items
will still be defined because it's an empty array, if you check post.capabilities.items.length
it should work fine because 0
is falsy.
post.capabilities.items
仍然会被定义,因为它是一个空数组,如果你检查post.capabilities.items.length
它应该可以正常工作,因为它0
是假的。
回答by Dmitri Pavlutin
Verify the length
property of the array to be greater than 0
:
验证length
数组的属性大于0
:
<p ng-if="post.capabilities.items.length > 0">
<strong>Topics</strong>:
<span ng-repeat="topic in post.capabilities.items">
{{topic.name}}
</span>
</p>
Arrays (objects) in JavaScript are truthy values, so your initial verification <p ng-if="post.capabilities.items">
evaluates always to true
, even if the array is empty.
JavaScript 中的数组(对象)是真值,因此即使数组为空,您的初始验证也<p ng-if="post.capabilities.items">
始终为true
。
回答by Grant
To overcome the null
/ undefined
issue, try using the ?
operator to check existence:
要克服null
/undefined
问题,请尝试使用?
运算符检查是否存在:
<p ng-if="post?.capabilities?.items?.length > 0">
Sidenote, if anyone got to this page looking for an Ionic Frameworkanswer, ensure you use
*ngIf
:<p *ngIf="post?.capabilities?.items?.length > 0">
旁注,如果有人进入此页面寻找Ionic Framework答案,请确保您使用
*ngIf
:<p *ngIf="post?.capabilities?.items?.length > 0">