gpt4 book ai didi

javascript - 当子元素为空时隐藏 DOM 中的父元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:07:12 25 4
gpt4 key购买 nike

<div>
<h1>Birds</h1>
<ul>
<li ng-if="bird.type === 'bird'"
ng-repeat="bird in creatures">{{bird.name}}</li>
</ul>
</div>

我有一个来自服务器的响应,我想把它放入列表中。但是当列表为空时,我需要隐藏这个 div 容器。例如,如果 bird.type === 'bird' 不在数组中 - 我想隐藏 div。但是我想在 ng-repeat 之后使用 bird,所以我不能在 div 上制作 ng-if="bird.type === 'bird'"。我可以检查 li 是否为空,然后隐藏 div 吗?

plunkr example

AngularJS ng-repeat handle empty list case - 这是不一样的。如果 li 为空,我不想隐藏它,我想在我有 h1 的地方隐藏父级 - 当 li 为空时。

最佳答案

您可以执行以下操作:

<div ng-if="hasBirds(creatures)">
<h1>Birds</h1>
<ul>
<li ng-if="bird.type === 'bird'"
ng-repeat="bird in creatures">{{bird.name}}</li>
</ul>
</div>

然后在 Controller /指令中,您可以添加 hasBirds 函数。

$scope.hasBirds = function(list){
return list.filter(function(item){return item.type === 'bird'}).length > 0;
}

这个 hasBirds 函数会经常被调用,但它允许您隐藏/显示存在的鸟的航向。

关于javascript - 当子元素为空时隐藏 DOM 中的父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38794479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com