Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ng如果检查数组是否为空_Javascript_Arrays_Angularjs - Fatal编程技术网

Javascript ng如果检查数组是否为空

Javascript ng如果检查数组是否为空,javascript,arrays,angularjs,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.capabiliti

如果数组中没有项,我正在使用的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>

主题:{{topic.name}


但是,我可能会完全偏离基准,因为这是我第一次在Angular中工作,可能有更好的方法来完成我正在尝试的工作。

post.capabilities。由于它是一个空数组,因此仍将定义项,如果您检查
post.capabilities.items.length
它应该可以正常工作,因为
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>

主题: {{topic.name}


JavaScript中的数组(对象)是真实的值,因此您的初始验证

总是计算为
true
,即使数组为空。

要克服
null
/
未定义的问题,请尝试使用
操作符检查是否存在:

<p ng-if="post?.capabilities?.items?.length > 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


尚未为搜索条件确定任何条款

不幸的是,如果数组为
null
undefined
,则此操作不起作用-我得到一个运行时错误。@Dai您找到了空数组的方法吗?正如公认的答案所指出的,只需使用:ng if=“post.capabilities.items.length”然后null、undefined和0 length都计算为false。
    emptyClause(array:any) {


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

            this.emptyMessage=false;

    }else{

            this.emptyMessage=true;
        }
}
        <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>