Angularjs - Inserting directives dynamically to dom element

試著忘記壹切 提交于 2020-04-30 07:34:07

问题


I'm trying to set a directive to my inputs accordingly.

So let's say I have this input:

<input type="foo" id="myinput" maskvalue> </input>

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', "");
}

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?

But that's basically the question, how can I insert a directive dynamically to a dom element?

Thanks


回答1:


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);
    }
}

Make sure you do this in an Angular controller that has $compile and $scope injected into it.



来源:https://stackoverflow.com/questions/38861425/angularjs-inserting-directives-dynamically-to-dom-element

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