1

I've got a testing routine that creates a div tag, appends it to the body, and then sets its innerHTML property to:

<p>{{testVar}}</p>

All with Javascript, like so:

var created = document.createElement('h1');

var elem = document.body.appendChild(created);
elem.innerHTML='<p>{{testVar}}</p>';

It then shows up on the page, double curly brackets and all. What is the correct way to dynamically add this single element to my page so that the interpolation is recognized?

1
  • That's a XY problem. Simply don't do that. Commented Sep 9, 2014 at 21:43

1 Answer 1

2

You have to compile the HTML against the current scope, you can use a directive:

app.directive("myDynamicHtml", ["$compile", function($compile) {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            var compiledHtml = $compile("<h1><p>{{testVar}}</p></h1>")(scope);
            document.body.appendChild(compiledHtml);
        }
    }
}]);
Sign up to request clarification or add additional context in comments.

3 Comments

It should be compiledHtml[0].
If I inject $compile into my Service service, can I $compile it there but against the $rootScope?
Yep, inject it where needed.

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.