AngularJS ng-if directive briefly renders even when condition is false before removing element

后端 未结 2 1701
野性不改
野性不改 2021-01-02 17:05

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

相关标签:
2条回答
  • 2021-01-02 17:24

    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.

    0 讨论(0)
  • 2021-01-02 17:44

    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.

    0 讨论(0)
提交回复
热议问题