compile angular on an element after angular compilation has already happened

*爱你&永不变心* 提交于 2019-12-21 03:03:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!