【问题标题】:AngularJS directive using templateURL loaded templateAngularJS 指令使用 templateURL 加载模板
【发布时间】:2014-11-11 17:30:36
【问题描述】:

我正在尝试创建一个指令,它将模板的内容动态添加到 DOM 中。就像 angular-datePicker 一样。

我希望有这样一个指令作为属性指令。例如,我会将它用于按钮。单击按钮时,将显示表单。 从技术上讲,我正在考虑使用链接函数,将回调绑定到元素 onClick 事件并使用 element.insertAfter 方法在该回调中添加模板内容。

问题是,我无权访问由 templateURL 加载的模板。第二个问题是属性指令的默认行为——它自动将模板附加为元素的子元素。有什么办法可以禁用吗?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    听起来你想要更多的自定义行为,这很容易在你的指令中编写脚本。

    基本步骤:

    1. 使用 $http 服务获取模板
    2. compile 模板 - 引用范围
    3. 将模板插入到 DOM 中的任意位置

      angular.module('myModule').directive('myDirective', function ($http, $compile) {
          var directive = {};
      
          directive.restrict = 'A';
          directive.link = function (scope, elem, attr) {
              var templateString = '';
      
              $http.get('[ path to template ]').then(function (response) {
                  templateString = response.data;
      
                  var compiledHtml = $compile(templateString)(scope); // compile with scope variables
      
                  element.append(compiledHtml); // change this around to insert your element into the DOM
              });
      
          };
      
          return directive;
      });
      

    【讨论】:

      猜你喜欢
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      相关资源
      最近更新 更多