2016-01-05 87 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 */ 
});