user309838 user309838 - 2 months ago 8x
HTML Question

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');
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?



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

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