Conditional ng-include together with ng-controller in AngularJS

早过忘川 提交于 2020-01-16 05:13:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26006588/conditional-ng-include-together-with-ng-controller-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!