user309838
user309838

Reputation: 357

Angularjs - Inserting directives dynamically to dom element

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

Upvotes: 1

Views: 2006

Answers (1)

Dr. Cool
Dr. Cool

Reputation: 3721

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.

Upvotes: 3

Related Questions