初始化昂贵的元素与NG-如果然后显示与NG-显示/隐藏/隐藏初始化、昂贵、元素、NG

2023-09-13 05:07:03 作者:长空夕醉

我有一个元素,它的产生是昂贵的。因此,我不使用它包含在初始页面加载:

I have an element whose generation is expensive. As such, I do not include it on initial page load using:

<div id='myExpensiveElement' ng-if='showElement'> 

如果用户点击一个特定的按钮:

If the user clicks a particular button:

<button ng-click='showElement = !showElement'>

的昂贵的元素被生成并插入到DOM。用户可以选择通过再次单击按钮隐藏元素。然而,这会导致从DOM中删除的元素,需要将其重新产生的。

the expensive element is generated and inserted into the DOM. The user may choose to hide that element by clicking the button again. However, this causes the element to be removed from the DOM, requiring it to be generated again.

有没有办法来NG-秀结合/隐藏与NG-如果这样,如果元素已经产生一次,切换使用NG-显示/隐藏,而不是NG-如果?

Is there a way to combine ng-show/hide with ng-if such that if the element has been generated once, switch to use ng-show/hide instead of ng-if?

推荐答案

一个简单的方法来做到这一点没有自定义指令是使用另一个变量来跟踪初始化...

A simple way to do this without a custom directive would be to use another variable to track the initialization...

<button ng-click='showElement = !showElement; elementInitialized = true'></button>
<div id='myExpensiveElement' ng-if='elementInitialized' ng-show='showElement'> 
...
</div>

小提琴