0

I am trying to render some html to the DOM that has AngularJS directives

HTML

<a ng-click="doThing()">hello 2015</a>

Except due to constraints in my application, I have to add it to the view from the controller. I am attempting to do this using the $compile service.

Controller.js

let html = '<a ng-click="doThing()">hello 2015</a>';

const compiledTemplate = $compile(html)($scope);

document.getElementById('wrapper').innerHTML = compiledTemplate[0].innerHTML;

$scope.doThing = function(){

    console.log('it worked!');
}

View.html

<div id="wrapper"></div> 

This renders the correct HTML but the directives dont work. Clicking on the link does not fire the doThing() function.

How can I compile and render a string representation of an AngularJS template such that all angular directives are functional?

1 Answer 1

1

Your code doesn't work because you're just copying the raw HTML string out of the compiled directive - none of the bindings are copied, just the string.

Best to call $compile() with a HTML element instead of with an HTML string, like this:

//find the wrapper DOM element
const directiveTarget = document.getElementById('wrapper');

//put the raw HTML into it
directiveTarget.innerHTML = '<a ng-click="doThing()">hello 2015</a>';

//get the angularjs-friendly version of the element
const directiveElement = angular.element(directiveTarget);

//initialise AngularJS bindings
const compiledTemplate = $compile(directiveElement)($scope);
Sign up to request clarification or add additional context in comments.

2 Comments

this was the solution. I dont know why I thought compiling the raw html would work. thank you!
Any time. Good luck with your project!

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.