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

后端 未结 2 1719
野性不改
野性不改 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:

    {{"Should not appear"}}

    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.

提交回复
热议问题