gpt4 book ai didi

javascript - 使用 Angular,如何仅在其 ID 与范围变量匹配时显示 DOM 元素?

转载 作者:行者123 更新时间:2023-11-29 19:39:53 27 4
gpt4 key购买 nike

我对 AngularJS 比较陌生。

我在部分 View 中有一系列 DIV。每个 DIV 都有一个唯一的 ID。我想根据范围值(与唯一 ID 之一匹配)显示/隐藏这些 DIV。

我可以使用 {{showdivwithid}} 之类的东西在 View 中成功写出范围值

隐藏所有 ID 不是 {{showdivwithid}} 的同级 div 的最干净的方法是什么

最佳答案

我认为您正在以 jQuery 思维方式解决问题。

最简单的解决方案是不使用每个 div 的 id 而使用 ngIf

<div ng-if="showdivwithid==='firstDiv'">content here</div>
<div ng-if="showdivwithid==='secondDiv'">content here</div>
<div ng-if="showdivwithid==='thirdDiv'">content here</div>

如果您不介意其他元素出现在 DOM 中,您可以将 ng-if 替换为 ng-show

或者使用像这样的小指令:

app.directive("keepIfId", function(){
return {
restrict: 'A',
transclude: true,
scope: {},
template: '<div ng-transclude></div>',
link: function (scope, element, atts) {
if(atts.id != atts.keepIfId){
element.remove();
}
}
};
});

HTML

<div id="el1" keep-if-id="{{showdivwithid}}">content here</div>
<div id="el2" keep-if-id="{{showdivwithid}}">content here</div>
<div id="el3" keep-if-id="{{showdivwithid}}">content here</div>

关于javascript - 使用 Angular,如何仅在其 ID 与范围变量匹配时显示 DOM 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795237/

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