具有模态的ng模板内的角度指令

Angular directive inside ng-template with modal

本文关键字:指令 模态 ng      更新时间:2023-09-26

我对angular使用预加载指令的方式感到好奇,因为我对驻留在<script>标记和ng模板中的指令有问题。

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

这是其他指令的html,包含有问题的myDirective

<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文件中,它就可以正常工作,并且控制器内部的代码会在启动时加载。我不确定如何解决这个问题。

根据我对这个问题的了解,您需要使用$compile服务。这里有一个教程可能会有所帮助:$compile

教程中给出的原因是:

"新铸造的模板没有赋予AngularJS力量然而这就是我们使用$compile服务的地方。。。"

引用自Angular Docs:

将一段HTML字符串或DOM编译为模板,并生成template函数,然后可以使用该函数链接scope和模板在一起。

以下是教程中的一个简短代码示例:

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 */
});