2016-01-05 89 views
3

我很好奇的角度工作与预加载指令,因为我有一个指令,存在于<script>标记和NG模板的问题。Angular指令内ng模板与模式

当我在chrome dev-tools中暂停执行时,在初始文档加载期间,我可以清楚地看到,如果我的指令位于某个任意模板中,指令控制器内的代码不会被调用。以下是示例代码,例如myDirective被包括在index.html作为Mymodule中的.js模块的一部分,无论是在索引和主应用程序模块中还包括:

这是包含有问题的myDirective

<script type="text/ng-template" id="callThis"> 
    <myDirective></myDirective> 
</script>` 
一些其他指示的HTML

和我一起ngDialog调用它的点击这样

ngDialog.open({ 
    template: 'callThis', 
    scope: $scope 
}); 

,它不能运行指令,因为它没有任何与HTML(TH工作ats错误,关于一些html元素丢失)。

最后这里是持有myDirective

angular.module('myModule', ['myDirectiveTemplates', 'myDirectiveDirective']) 
angular.module('myDirectiveTemplates', []).run(["$templateCache", function($templateCache) {$templateCache.put("myDirectiveTemplate.html","<h1></h1>");}]); 
angular.module('myDirectiveDirective', []).directive('myDirective', function ($window, $templateCache) { 
    return { 
    restrict: 'E', 
    template: $templateCache.get('myDirectiveTemplate.html'), 
    controller: function($scope) { 
     //some arbitrary code 
    } 
    }; 
}) 

有趣的是,如果我就在index.html文件它的工作原理确定把<my-directive></my-directive>模块的代码,并在控制器内的代码被加载上启动。我不确定如何解决这个问题。

+0

我有相同的困难。你设法解决它吗? –

回答

1

从我所了解的这个问题你需要使用$ compile服务。这里有一个教程,可以帮助:$编译

在本教程中给出的原因是:

“新崛起的模板还没有被赋予了AngularJS权力 但在这里,我们使用$编译服务......”

而且从角文档引用:

编译一段HTML字符串或DOM的成模板和生产线使用一个 模板函数,然后可以使用该函数将示波器和 模板链接在一起。

下面是一个简短的代码示例具体根据教程:

app.directive('contentItem', function ($compile) { 
    /* EDITED FOR BREVITY */ 

    var linker = function(scope, element, attrs) { 
     scope.rootDirectory = 'images/'; 

     element.html(getTemplate(scope.content.content_type)).show(); 

     $compile(element.contents())(scope); 
    } 

    /* EDITED FOR BREVITY */ 
});