【问题标题】:How to call directive from template html in angularjs如何在angularjs中从模板html调用指令
【发布时间】:2016-05-17 19:24:22
【问题描述】:

HTML

<script type="text/ng-template" id="ProfileTemplateHTML" >
    <div class="container profilepopup-cont" align="center">
        <div class="row">
            <div class="col-sm-3 zero-margin-padding" align="center">
                <img id="DisplayImage" ng-src={{model.picLarge}} class="img-circle">
            </div>
...
</script> 

在这个 html 模板文件中,我必须调用一个指令。我的指令名称是“帮助”。但如果我添加调用该指令,它就不起作用。 如何在angularjs中调用html模板内的指令?

【问题讨论】:

  • 如果我使用 来调用 html 中的指令,它不起作用
  • 在模板内编译模板指令后将起作用。您可以使用 $compile 服务手动编译它
  • @murli2308 能告诉我如何手动编译吗?
  • 你的问题不是很清楚。 “不工作”是什么意思?没有理由不能在模板中使用指令;为了了解您的问题,我们需要知道您是如何调用此模板的。
  • 同时提供指令JS代码。指令的名称是什么?正确的名称(在 JS 文件中定义)应该是 profilepopupCont(而不是 profilepopup-cont)。指令restrict 属性是什么?它应该包括“A”。

标签: angularjs angularjs-directive


【解决方案1】:

您可以通过这些方式添加指令

  1. 作为属性

<div help>
 ...
  
 </div>
  1. 作为单独的标签

<page>
  
  //your code
  
</page>

【讨论】:

  • 你也可以通过 &lt;span class="help"&gt;&lt;/span&gt; 的课程和评论 &lt;!-- help --&gt; 来做到这一点。
  • 她的问题不是关于如何在 html 中定义指令,她的问题是为什么它在 ng-template 中不起作用。
  • 我已经尝试将它保存在 div,page,span 中。它不起作用!
  • 指令也可以通过设置任意标签的类来应用。
【解决方案2】:

我不确定我是否完全理解这个问题。 here 是一个 jsfiddle,用于演示如何在 ng-template 中使用自定义指令。

或者试试这个..

angular.module('demo', [])
  .directive('help', function() {
    return {
      template: '<div>Help! {{info}}</div>',
      scope: {
        info: '@info'
      }
    };
  })
  .controller('MainCtrl', ['$log',
    function($log) {
      this.hello = 'This is MainCtrl';
      this.template = 'profile-template.html';

      //construct
      $log.debug('DemoCtrl has been loaded');
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="demo">
  <script type="text/ng-template" id="profile-template.html">
    <div>this is profile-template.html</div>
    <div help info="this is directive info."></div>
  </script>
  <div ng-controller="MainCtrl as main">
    <h2>just a demo</h2>
    <div>{{main.hello}}, include template from {{main.template}}</div>
    <hr>
    <div ng-include src="main.template"></div>
  </div>

</body>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多