问题
I'm writing a directive and when clicked it loads a html template from the server. How can I get angular to compile this?
EDIT: I should probably mention the template is used for loading into a modal.
回答1:
You can inject the $compile service and $compile it whenever you want. $compile('<p>{{total}}</p>')(scope)
is the example from the docs.
In practice you'll probably want to do something like this:
//Example as a directive's link function
function link(scope, element, attributes){
scope.name = "world";
template = "<p>hello {{name}}</p>"; //this could come from anywhere
element.html(template);
$compile(element.contents())(scope);
}
This example appends the compiled contents instead of replacing it:
function link(scope, element, attributes){
scope.something = "this is bananas";
$compile("<p>{{something}}</p>")(scope, function(cloned, scope){
element.append(cloned);
});
}
来源:https://stackoverflow.com/questions/18064543/compile-angular-on-an-element-after-angular-compilation-has-already-happened