AngularJS-将指令动态插入dom元素 [英] Angularjs - Inserting directives dynamically to dom element
问题描述
我正在尝试相应地为输入设置指令.
I'm trying to set a directive to my inputs accordingly.
所以说我有这个输入:
<input type="foo" id="myinput" maskvalue> </input>
这在我的应用程序上正常运行,问题是当我尝试使用"setAttribute"动态插入"maskvalue"时,它不起作用,这是我现在要尝试的操作:
This works fine on my app, the problem is when I try to insert "maskvalue" dynamically using the "setAttribute" it doesn't work, here's what I'm trying to do right now:
element = document.getElementById('myinput');
if(element){
element.setAttribute('maskvalue', "");
}
此代码将成功地将我的指令插入dom元素,但不会生效.似乎在已加载dom的情况下无法向dom插入自定义指令,我错了吗?
This code will successfully insert my directive to the dom element, but will take no effect. It seems that is impossible to insert a custom directive to the dom when it was already loaded, am I wrong?
但这基本上是问题,我如何动态地将指令插入dom元素?
But that's basically the question, how can I insert a directive dynamically to a dom element?
谢谢
推荐答案
使用Angular的 $ compile
命令对此进行Angular化.基本上,您需要通知Angular您已进行了更改,以便它可以发挥其魔力.
Use Angular's $compile
command to Angular-ize this. Basically, you need to notify Angular that you have made a change so it can do its magic.
function MyController($scope, $compile) {
element = document.getElementById('myinput');
if (element) {
element.setAttribute('maskvalue', "");
$compile(element)($scope);
}
}
确保您在已插入 $ compile
和 $ scope
的Angular控制器中执行此操作.
Make sure you do this in an Angular controller that has $compile
and $scope
injected into it.
这篇关于AngularJS-将指令动态插入dom元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!