简体   繁体   English

在Angular Bootstrap之后向DOM添加指令

[英]Adding a directive to the DOM after Angular bootstrap

I´m trying to add some directives to the DOM after Angular has bootstrapped. 我试图在Angular启动后向DOM添加一些指令。 If I do this in the run block it perfectly works, however if I add a delay the directive is not shown. 如果在运行块中执行此操作,则它会完美运行,但是如果添加延迟,则不会显示该指令。 Check out my Fiddle so you can see what i mean: https://jsfiddle.net/wLddmctp/ 查看我的小提琴,这样您就可以明白我的意思了: 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);
});

Can someone explain whats the reason for this, and how to solve this problem? 有人可以解释这是什么原因,以及如何解决这个问题吗?

Thanks 谢谢

You will need to compile new HTML manually, because if you use it in timeout Angular has already finished parsing and rendering. 您将需要手动编译新的HTML,因为如果在超时中使用它,Angular已经完成了解析和渲染。

So you need to use $compile service with correct scope. 因此,您需要使用具有正确范围的$compile服务。

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

Demo: https://jsfiddle.net/wLddmctp/1/ 演示: https : //jsfiddle.net/wLddmctp/1/

That being said, you can see that code becomes a little clumsy with such usage of $compile and especially getting proper element scope. 话虽如此,您可以看到$compile这样的用法使代码变得笨拙,尤其是获得适当的元素范围。 I would recommend to use custom service/directive for dynamic injection of HTML, run block is not ideal place for this. 我建议对HTML的动态注入使用自定义服务/指令,运行块不是理想的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM