AngularJS:如何从另一个控制器内动态初始化模板中的控制器

时间:2014-12-25 12:59:27

标签: angularjs angularjs-controller angularjs-templates

我希望ChildCtrl仅在单击上方的按钮时进行初始化。怎么可能?

<div ng-controller="ParentCtrl">
    <button>CLICK TO INIT CHILD CTRL</button>
    <div class="child-container">
        <div ng-controller="ChildCtrl" ng-include="'templates/child.html'" />
    </div>
</div>

1 个答案:

答案 0 :(得分:3)

这很简单,请使用ng-if:

<div ng-controller="ParentCtrl">
    <button ng-click='loadChild=true'>CLICK TO INIT CHILD CTRL</button>
    <div class="child-container" ng-if='loadChild'>
        <div ng-controller="ChildCtrl" ng-include="'templates/child.html'" />
    </div>
</div>
除非表达式为ng-if,否则

true指令不会加载DOM。