条件ng-include与AngularJS中的ng-controller一起使用 [英] Conditional ng-include together with ng-controller in AngularJS
问题描述
我有一个条件 ng-include
指令与 ng-controller
相关联,但似乎控制器不是在条件为真时运行。
目标是仅在条件满足时包含模板并避免 TypeError:无法调用null
问题的方法'insertBefore' 。
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.
例如:
<div ng-include src="myContent.imgList ? 'ui/image-list.html' : null" ng-controller="ImgListSubCtrl">
</div>
当 myContent.imgList
填充数据时,我希望将 image-list.html
模板附加到DOM并运行 ImgListSubCtrl
,但它不是。
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.
这是预期的行为吗?我正在使用带有Angular 1.2.17的Ionic Framework。
Is this the expected behavior?. I'm using Ionic Framework with Angular 1.2.17.
谢谢。
推荐答案
我已经找到了解释,但欢迎进一步的评论。
I already found an explanation, though further comments are welcome.
以下Codepen显示了上述行为和解决方案(在Ionic Framework 1.0.0-中beta12): http://codepen.io/anon/pen/FnojD?editors=101
第一个包含不显示任何计数,但第二个显示正确。
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.
似乎在使用<$时c $ c> ng-include 以及 ng-controller
,控制器只运行一次,即使 ng -include src
expression的计算结果为 null
。
在实际包含模板时运行它(<$ c $时c> ng-include src 不是 null
),解决办法是避免条件 ng-include
并将其包装在 ng-if
块中,以便谁le元素是动态重新创建的,如上面的Codepen中所示。
在问题的示例中:
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>
我希望它有所帮助。
这篇关于条件ng-include与AngularJS中的ng-controller一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!