在Angular引导后向DOM中添加一个指令

Adding a directive to the DOM after Angular bootstrap

本文关键字:指令 一个 添加 Angular DOM      更新时间:2023-09-26

我试图在Angular启动后向DOM添加一些指令。如果我在运行块中这样做,它会完美地工作,但是如果我添加延迟,则不会显示指令。看看我的小提琴,你就能明白我的意思了:https://jsfiddle.net/wLddmctp/

var app = angular.module("myApp", ["docsSimpleDirective"]);
app.run(function ($timeout) {
    $timeout(function () {
        var container = document.getElementById("container");
        var box = document.createElement("div");
        box.innerHTML = "<div my-customer></div>";
        container.appendChild(box);
    }, 3000);
});

谁能解释一下这是什么原因,以及如何解决这个问题?

谢谢

你需要手动编译新的HTML,因为如果你在timeout中使用它,Angular已经完成了解析和渲染。

所以你需要使用正确作用域的$compile服务。

var scope = angular.element(container).scope();
$compile(box)(scope);
演示:

https://jsfiddle.net/wLddmctp/1/

话虽这么说,但您可以看到,使用$compile,特别是获得适当的元素作用域,代码变得有点笨拙。我建议使用自定义服务/指令来动态注入HTML,运行块不是理想的地方。