在 ng-include 中动态加载的 AngularJS 指令不起作用

在 ng-include 中动态加载的 AngularJS 指令不起作用

问题描述:

我有一个自定义指令,它添加了一些 html.

I have a custom directive which adds some html.

myAppModule.directive('myDirective', function() {
    var linker = function(scope, element) {
        return element.html("<b>directive loaded</b>");
    };
    return {
        restrict: "E",
        rep1ace: true,
        link: linker,
        scope: false
    };
});

此指令在动态加载的 html 中加载和使用,该 html 通过 ng-include 包含.

This directive is loaded and used in a dynamically loaded html which is included via ng-include.

<script type="text/javascript" src="dynamicscript.js"></script>
<my-directive>...</my-directive>

但它不起作用.linker 函数永远不会被调用.如果我将 dynamicscript.js 脚本加载从包含的 html 移动到 index.html,它会起作用.

But it does't work. The linker-function is never called. It works if I move the dynamicscript.js script loading from the included html to the index.html.

这是 Plunkr

只需使用 RequireJS 来加载控制器、指令,等等.

Just use RequireJS to load the controllers, directives, and so on.

使用特殊插件,也可以加载 CSS 和 HTML 文件.

Using special plugins, CSS and HTML files can be loaded too.

这是 Ben Nadel 的一个很好的例子:http://www.bennadel.com/blog/2554-Loading-AngularJS-Components-With-RequireJS-After-Application-Bootstrap.htm

Here is a great example from Ben Nadel: http://www.bennadel.com/blog/2554-Loading-AngularJS-Components-With-RequireJS-After-Application-Bootstrap.htm