AngularJS - 动态创建指定指令元素 [英] AngularJS - Dynamically creating elements that specify directives
问题描述
我有这样的设置:
- 控制器
C
广播事件电子
- 指令
D
监听电子
,并在电子
通过追加写入DOM,并在这样做,创造了新的元素指定指令D 2
。
- Controller
c
broadcasts evente
- Directive
d
listens fore
, and one
, writes to the DOM via append, and in so doing, creates new elements specifying a directived2
.
IE: element.append('< directiveTwo ...>')
- 指令
两个
永远不会被称为角 - 当我检查DOM(和调试)我看到控制器
C
和指导D
正在做他们的工作,我有新的directiveTwo
元素。
- Directive
two
is never called by Angular - When I inspect the DOM (and debug) I see that Controller
c
and directived
are doing their jobs, and I have newdirectiveTwo
elements.
缺少什么?需要采取哪些措施来触发指令 2
调用后动态创建这些元素?
What is missing? What needs to be done to trigger the directive 2
call after dynamically creating those elements?
推荐答案
请参见 $编译
。您同样可以使用此服务的:
See $compile
. You can use this service similarly to this:
var newDirective = angular.element('<div d2></div>');
element.append(newDirective);
$compile(newDirective)($scope);
这将执行新元素的编译和链接,并设置 D 2
付诸行动。
This will perform the compilation and linking of your new element, and set d2
into action.
然而,你可能会发现它更简单,更棱角分明,如果你能以某种方式重写你原来的指令建于指令如的其他条款NG-重复
或 NG-包括
将执行编译和链接给你的。
However you may find it simpler and more angular if you can somehow rewrite your original directive in terms of other built in directives like ng-repeat
or ng-include
that will perform the compile and link for you.
如果您的指令是很简单的它可能只是做沿着听到你的事件,当添加到一个数组的东西线,并指定像
If your directive is simple enough it could just do something along the lines of adding to an array when hearing your event, and specify a template like
<div ng-repeat="evt in recordedEvents">
<div d2="evt"></div>
</div>
这篇关于AngularJS - 动态创建指定指令元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!