ng-if检查数组是否为空

时间:2016-01-27 15:37:02

标签: javascript arrays angularjs

如果数组中没有项目

,我正在使用的API会返回此值
items: []

如果数组中有项目,则返回类似

的内容
items: [
  {
    name: 'Bla'
  }
]

在我的模板中,我认为我需要使用ng-if根据是否有数据来显示/隐藏元素。

<p ng-if="post.capabilities.items"><strong>Topics</strong>: <span ng-repeat="topic in post.capabilities.items">{{topic.name}}</p>

然而,我可能完全偏离基础,因为这是我第一次在Angular工作,并且可能有更好的方法来做我想做的事。

4 个答案:

答案 0 :(得分:71)

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

答案 1 :(得分:31)

验证数组的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>

JavaScript中的数组(对象)是真实值,因此即使数组为空,您的初始验证<p ng-if="post.capabilities.items">也会始终评估为true

答案 2 :(得分:10)

要解决null / undefined问题,请尝试使用?运算符检查存在:

<p ng-if="post?.capabilities?.items?.length > 0">
  • 旁注,如果有人到这个页面寻找 Ionic Framework 的答案,请确保使用*ngIf

    <p *ngIf="post?.capabilities?.items?.length > 0">
    

答案 3 :(得分:0)

以我的经验,在HTML模板上执行此操作非常困难,因此我决定使用事件在TS上调用函数,然后检查条件。如果为true,则条件等于true,然后在HTML的ngIf上使用该变量

    emptyClause(array:any) {


        if (array.length === 0) {
            // array empty or does not exist

            this.emptyMessage=false;

    }else{

            this.emptyMessage=true;
        }
}

HTML

        <div class="row">

        <form>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
            <div class="col-md-10 col-sm-10 col-xs-10">
        <div [hidden]="emptyMessage" class="alert alert-danger">

            No Clauses Have Been Identified For the Search Criteria

        </div>
            </div>
            <div class="col-md-1 col-sm-1 col-xs-1"></div>
        </form>

相关问题