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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:12:29  来源:igfitidea点击:

ng-if check if array is empty

javascriptarraysangularjs

提问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.itemswill still be defined because it's an empty array, if you check post.capabilities.items.lengthit should work fine because 0is falsy.

post.capabilities.items仍然会被定义,因为它是一个空数组,如果你检查post.capabilities.items.length它应该可以正常工作,因为它0是假的。

回答by Dmitri Pavlutin

Verify the lengthproperty 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/ undefinedissue, 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">