【问题标题】:Angular directive inside ng-template with modal带有模态的ng-template内的Angular指令
【发布时间】: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
    }
  };
})

有趣的是,如果我将&lt;my-directive&gt;&lt;/my-directive&gt; 放在 index.html 文件中,它可以正常工作,并且控制器内的代码会在启动时加载。我不确定如何解决这个问题。

【问题讨论】:

  • 我也遇到了同样的困难。你解决了吗?

标签: javascript jquery html angularjs


【解决方案1】:

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

教程中给出的原因是:

"新创建的模板并没有被赋予 AngularJS 的权力 然而。这是我们使用 $compile 服务的地方..."

并引用自 Angular 文档:

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

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2020-03-26
    • 1970-01-01
    • 2023-03-05
    • 2015-08-20
    • 2014-10-26
    相关资源
    最近更新 更多