AngularJS: How to dynamically initialize a controller in a template from within another controller

1.4k Views Asked by At

I would like ChildCtrl to be initialized only when the button above it is clicked. how is that possible?

<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

There are 1 best solutions below

1
On BEST ANSWER

That is easy, use 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 directive does not load the DOM unless the expression is true.