AngularJS ng-if directive briefly renders even whe

2019-02-09 19:11发布

问题:

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

回答1:

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.



回答2:

I think that false expression is not well converted to angular false. I can prove this by setting:

<div ng-if="!true">

Which doesn't render text in current div. Anyway, it executes alert, i suppose it is executed before angular runs, that's why.