【发布时间】:2016-01-05 21:40:42
【问题描述】:
我对 Angular 与预加载指令一起工作的方式感到好奇,因为我对位于 <script> 标记和 ng-template 中的指令有疑问。
当我在 chrome 开发工具中暂停执行时,在初始文档加载期间,我可以清楚地看到,如果我的指令位于某个任意模板中,则指令控制器内的代码不会被调用。这是示例代码,例如myDirective 作为 myModule.js 模块的一部分包含在 index.html 中,也包含在 index 和主应用程序模块中:
这是包含有问题的 myDirective 的其他指令的 html
<script type="text/ng-template" id="callThis">
<myDirective></myDirective>
</script>`
我用这样的 ngDialog 调用它
ngDialog.open({
template: 'callThis',
scope: $scope
});
并且它无法运行该指令,因为它没有任何 html 可以使用(这就是错误,关于缺少一些 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
}
};
})
有趣的是,如果我将<my-directive></my-directive> 放在 index.html 文件中,它可以正常工作,并且控制器内的代码会在启动时加载。我不确定如何解决这个问题。
【问题讨论】:
-
我也遇到了同样的困难。你解决了吗?
标签: javascript jquery html angularjs