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

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

问题描述

在下面的模板中,我希望脚本标签永远不会呈现,警报脚本永远不会执行.然而它确实如此.

<script>alert('should not run')</script>不应该出现

这给我们在移动设备上造成了巨大的性能问题,因为我们在 ng-if 中包装了大型 DOM 和指令结构,期望它们在条件为假时不会呈现.

我也测试了 ng-switch 的行为方式相同.

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

JSFiddle

解决方案

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

如果您不希望内部 DOM 呈现,请将其放置在指令中(可以是它自己的指令,也可以通过 ng-include)或视图中.

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

为了帮助自己更好地理解流程,您可以将示例更新为:

{{"不应该出现"}}<script>alert('should not run')</script>

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

您会注意到,当警报弹出时,Angular 尚未插入不应出现"(它出现在大括号中).但是,在您解除警报后,它就会消失.

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

指令中隐藏不应该运行"的代码的例子可以在这里查看:https://jsfiddle.net/hLw0nady/4/

在此示例中,只有将 ng-if="false" 替换为 ng-if="true" 时,您才会收到警报.

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>

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.

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

解决方案

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).

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.

Example 1 (understanding why the script runs):

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/

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.

Example 2 (how to prevent the alert):

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

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

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

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