AngularJS ng-if指令在删除元素之前即使条件为false也会短暂呈现 [英] AngularJS ng-if directive briefly renders even when condition is false before removing element

查看:109
本文介绍了AngularJS ng-if指令在删除元素之前即使条件为false也会短暂呈现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的模板中,我希望脚本标记永远不会呈现,并且警报脚本永远不会执行。但它确实如此。

In the below template, I would expect the script tag to never render, and the alert script to never execute. However it does.

<div ng-if="false">
    <script>alert('should not run')</script>
    Should not appear
</div>

这导致我们在移动设备上出现巨大的性能问题,因为我们在<$中包装大型DOM和指令结构c $ c> ng-if s期望当条件为假时它们不会呈现。

This is causing us huge performance problems on mobile devices as we wrap large DOM and directive structures in ng-ifs with the expectation they will not render when the condition is false.

我还测试了 ng-switch 其行为方式相同。

I have also tested ng-switch which behaves in the same manner.

这是预期的行为吗?有没有办法避免不必要的渲染?

Is this expected behaviour? Is there a way to avoid the unnecessary render?

JSFiddle

推荐答案

它可能看起来很落后,但 ngIf 处理更多删除DOM,而不是添加。在控制器完成实例化之前,DOM仍然存在。这通常是一件好事,并且允许您在没有JS的情况下(或者,初始加载状态)优雅地降级。

It may seem backward, but ngIf deals more with the removal of DOM, rather than the addition. Before the controller finishes instantiating, the DOM still exists. This is generally a good thing, and allows you to have graceful degradation for users without JS (or, alternatively, an initial loading state).

如果您不想要要呈现的内部DOM,将其放在指令(自己的指令,或通过 ng-include )或视图中。

If you don't want the inner DOM to render, place it in a directive (either its own directive, or via ng-include) or in a view.

示例1(了解脚本运行的原因):

帮助自己了解流程更好一点,您可以更新示例而不是:

To help yourself understand the flow a bit better, you can update the example to instead be:

<div ng-if="false">
    {{"Should not appear"}}
    <script>alert('should not run')</script>
</div>    

https://jsfiddle.net/hLw0nady/6/embedded/result/

当警报弹出时,您会注意到up,Angular还没有内插不应该出现(它出现在括号中)。然而,在您解除警报后,它会消失。

You will notice that when the alert pops up, Angular has not yet interpolated "Should not appear" (it appears in its braces). After you dismiss the alert, however, it disappears.

示例2(如何阻止警报):

可以在此处查看隐藏指令中不应该运行的代码的示例: https://jsfiddle.net/hLw0nady/4/

An example of hiding the code that "should not run" in a directive can be viewed here: https://jsfiddle.net/hLw0nady/4/

在这个例子中,只有当您用 ng-if =true替换 ng-if =false时才会收到警报。

In this example, only if you replace ng-if="false" with ng-if="true" will you get your alert.

这篇关于AngularJS ng-if指令在删除元素之前即使条件为false也会短暂呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆