1

I have a conditional ng-include directive with a ng-controller associated, but it seems the controller isn't run when the condition is true.
The target is to include the template only when the condition is met and avoid the TypeError: Cannot call method 'insertBefore' of null issue.

For example:

<div ng-include src="myContent.imgList ? 'ui/image-list.html' : null" ng-controller="ImgListSubCtrl">
</div>

When myContent.imgList is filled with data, I expect the image-list.html template to be appended to the DOM and ImgListSubCtrl to be run, but it isn't.

Is this the expected behavior?. I'm using Ionic Framework with Angular 1.2.17.

Thank you.

Community
  • 1
  • 1
rbarriuso
  • 787
  • 8
  • 30

1 Answers1

2

I already found an explanation, though further comments are welcome.

The following Codepen shows the mentioned behavior and the solution (in Ionic Framework 1.0.0-beta12): http://codepen.io/anon/pen/FnojD?editors=101
The first include doesn't display any count, though the second one displays it correctly.

It seems that when using ng-include along with ng-controller, the controller is only run once, even when the ng-include src expression evaluates to null.
To run it when the template is actually included (when ng-include src isn't null), a solution is to avoid the conditional ng-include and wrap it in a ng-if block, so the whole element is re-created dynamically, as shown in the Codepen above.
In the example from the question:

<div ng-if="myContent.imgList">
    <div ng-include src="'ui/image-list.html'" ng-controller="ImgListSubCtrl">
    </div>
</div>

I hope it helps.

rbarriuso
  • 787
  • 8
  • 30