如何通过 jQuery 的 .append() 添加 DOM 元素(Angular 指令)? [英] How to add DOM Elements (Angular directives) via jQuery's .append()?
问题描述
有什么方法可以使用 append()
等 jQuery 方法添加 Angular 指令的元素,并让 Angular 进行编译/链接以使其工作,就像您已包含该指令一样首先?
Is there any way to add an element that is an Angular directive with jQuery methods like append()
and have Angular do its compilation/linking to make it work as though you'd included the directive in the first place?
示例:
app.directive('myAngularDirective', [function () {
...
// Lots of stuff in here; works when used normally but not when added via jQuery
});
$("body").append("<my-angular-directive />");
它目前只是附加了一个名为my-angular-directive"的空 DOM 元素,但 Angular 并没有发挥作用并发挥它的魔力.
It currently just appends an empty DOM element called "my-angular-directive," but Angular doesn't kick in and do its magic.
推荐答案
正确的做法是使用:$编译,如果您的指令返回:directive definition object
(顺便说一句,推荐的方法)然后您可以在其上调用 link
函数(以例如注入 scope
).
The right way to go is to use: $compile and in case your directive returns: directive definition object
(which is btw. the recommended way to go) you can then call link
function on it (to inject scope
, for example).
$('body').append($compile("<my-angular-directive />")(scope));
scope.$apply();
这篇关于如何通过 jQuery 的 .append() 添加 DOM 元素(Angular 指令)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!