2

I have a code that dynamically create elements (the x and the parentDiv).

var x = document.createElement('myTag');
parentDiv.appendChild(x);

And I have a directive that looks like this:

.directive("myTag", function($compile) {
    return {
        restrict: "E",
        replace: true,
        template: "<span><img src='something/url/img.png'></img></span>"
    }
})

How can I replace the myTag tag into that code in the directive? I am aware of using $compile so that the code outside of AngularJS can be covered under its scope but I do not know where to put that.

4
  • Where are you creating this element? Outside of angular context? In a controller? In a factory? Commented Jan 18, 2017 at 9:43
  • @FealroneAlajas, did my answer help? Commented Jan 19, 2017 at 7:40
  • @Maximus hi. yes. sorry i was a bit today but it works like a charm. thanks! :D Commented Jan 19, 2017 at 9:13
  • @FealroneAlajas, great, good luck Commented Jan 19, 2017 at 9:45

1 Answer 1

1

Actually, you should use compile before appending your element:

var childScope = scope.$new();
var x = document.createElement('myTag');
var compiled = $compile(x)(childScope);
parentDiv.appendChild(compiled);

The $compile service will fetch the template:

<span><img src='something/url/img.png'></img></span>

and put it inside the DOM element referenced with x.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.