Tuesday, 20 August 2013

Angular.js's $compile doesn't replace values

Angular.js's $compile doesn't replace values

I'm build an Angular.js app that uses a third-party library. The library
requires me to pass in a string containing HTML. This HTML is complex and
requires several values to be injected. I'd like to use Angular's build in
$compile service to compile that data. Here's an example:
// create the template
var template = "<p>{{ test }}</p>";
// set up the scope
var scope = $rootScope.$new();
scope.test = "hello";
// compile the template
var htmlString = $compile(template)(scope)[0].outerHTML;
When I run this code, I would expect htmlString to be <p>hello</p>, but
instead it's <p class="ng-scope ng-binding">{{ test }}</p>. I understand
Angular is setting up its bindings, but I want static content. Is there
any way to achieve the behavior I want?

No comments:

Post a Comment