本文介绍了如何通过jQuery的.append()添加DOM元素(Angular指令)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过append()之类的jQuery方法添加作为Angular指令的元素,并让Angular进行编译/链接以使其工作,就像您首先将指令包括在内一样? >

示例:

app.directive('myAngularDirective', [function () {
    ...
    // Lots of stuff in here; works when used normally but not when added via jQuery
});

$("body").append("<my-angular-directive />");

当前,它只是附加了一个空的DOM元素,称为"my-angular-directive",但Angular不会加入并发挥其魔力.

解决方案

正确的方法是使用: $编译,如果指令返回:directive definition object(这是推荐的方法),则可以在其上调用link函数(例如,注入scope).

$('body').append($compile("<my-angular-directive />")(scope));
scope.$apply();

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?

Example:

app.directive('myAngularDirective', [function () {
    ...
    // Lots of stuff in here; works when used normally but not when added via jQuery
});

$("body").append("<my-angular-directive />");

It currently just appends an empty DOM element called "my-angular-directive," but Angular doesn't kick in and do its magic.

解决方案

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指令)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:59