Javascript 在AngularJS中动态创建元素后的绑定指令
我有一个动态创建元素的代码(Javascript 在AngularJS中动态创建元素后的绑定指令,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我有一个动态创建元素的代码(x和parentDiv) 我有一个指令,看起来像这样: .directive("myTag", function($compile) { return { restrict: "E", replace: true, template: "<span><img src='something/url/img.png'></img></span>" } }) 指
x
和parentDiv
)
我有一个指令,看起来像这样:
.directive("myTag", function($compile) {
return {
restrict: "E",
replace: true,
template: "<span><img src='something/url/img.png'></img></span>"
}
})
指令(“myTag”,函数($compile){
返回{
限制:“E”,
替换:正确,
模板:“”
}
})
如何将myTag标记替换为指令中的代码?
我知道使用$compile可以将AngularJS之外的代码包含在其范围内,但我不知道该放在哪里。实际上,在添加元素之前,您应该使用
compile
:
var childScope = scope.$new();
var x = document.createElement('myTag');
var compiled = $compile(x)(childScope);
parentDiv.appendChild(compiled);
$compile
服务将获取模板:
<span><img src='something/url/img.png'></img></span>
并将其放在用
x
引用的DOM元素中,您在哪里创建此元素?在角度背景之外?在控制器中?在工厂里?@FealroneAlajas,帮了忙吗?@Maximus嗨。对对不起,我今天有点紧张,但它很有魅力。谢谢D@FealroneAlajas,太好了,祝你好运
<span><img src='something/url/img.png'></img></span>