myVar 绑定到哪个元素? `ng-init` 的问题

Which element does myVar bind to? Problems with `ng-init`

我想知道使用 ng-init 时幕后发生了什么。

有时候ng-init会做一些意想不到的事情,调试起来很费劲


假设我有以下结构:

<!-- App -->
<div ui-view>

    <!-- Component -->
    <custom-component>

        <!-- Transcluded component -->
        <transcluded-component>

            <!-- Controller -->
            <div ng-controller="MyCtrl">

                <!-- Element -->
                <div ng-init="myVar = 'hello'">

                    {{myVar}}

                </div>
            </div>
        </transcluded-component>
    </custom-component>
</div>

myVar绑定到哪个元素?


编辑 2017-07-21:添加了示例

在下面的模板块中(尤其是在 ng-repeat 中),我可能会使用 ng-init:

<span ng-init="path = getPath()">
    <a ng-if="path" ng-href="path">
        Click here
    </a>
    <span ng-if="!path">
        Some text
    </span>
</span>

在这种情况下,我跳过了两次函数调用,并保持模板干净。

有时候ng-init会做一些意想不到的事情,调试起来很费劲

ng-init directive 在其元素范围的上下文中计算 Angular 表达式。许多指令(ng-repeatng-controllerng-ifng-view 等)创建了它们自己的范围。

有关详细信息,请参阅


避免使用 ng-init

避免使用 ng-init。它混淆了模型和视图,使代码难以理解、调试和维护。而是在控制器中初始化模型。

来自文档:

ngInit

This directive can be abused to add unnecessary amounts of logic into your templates. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, as seen in the demo below; and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope.

— AngularJS ng-init Directive API Reference


更新

Q: I've also added an example of a code block I sometime use.

        <!-- Controller -->
        <div ng-controller="MyCtrl">
            <!-- Element -->
            <div ng-init="myVar = 'hello'">
                {{myVar}}
            </div>
        </div>

在控制器中进行等效的初始化:

app.controller("MyVar", function($scope) {
    this.$onInit = function() {
        $scope.myVar = 'hello';
    };
});

通过Model和View的separating concerns,代码变得更容易理解、调试和维护。