繁体   English   中英

将指令转移到子DOM元素

[英]Transfer Directives to Child DOM Elements

我创建了一个自定义指令,该指令实际上是带有一些扩展标记的文本框。

module.directive("inputField", ["$log", function($log) {
    return {
      restrict: "E",
      replace: true,
      scope: {
        labelText: "@"
      },
      templateUrl: "input-field.template.html"
    }
  }]);

模板文件:

<div class="fancy-field">
  {{ labelText }}:
  <input type="text">
</div>

我希望我的指令支持添加标准HTML5输入属性和Angular指令,并将其应用于子输入。 我通过将选定的属性从父<div>元素转移到指令的编译函数中的内部<input>来完成此操作。

  compile: function(element, attributes) {

    var inputElement = $(element.children("input")[0]);
    if(attributes.innerDirective) {

      // Transfer the inner-directive element specified on the parent
      // to the child input
      inputElement.attr("inner-directive", attributes.innerDirective);

      // Remove the attribute specified on the outer element
      // in a futile attempt to keep the inner-directive
      // from applying to the outer div
      $(element).removeAttr("inner-directive");
      delete attributes.innerDirective;
      delete attributes.$attr.innerDirective;

    }

    return {};

  }

这成功地将受支持的属性和指令应用于<input> ,并且还从DOM的外部元素中删除了这些属性。 但是,它不会阻止将指令应用于内部和外部元素。 我希望能够对此进行控制,以便可以将支持的输入指令(例如ng-pattern)传输到我的输入中,而不会对外部div产生任何副作用。 我还希望避免不必要的处理我不想使用的指令的开销。

我创建了一个Plunkr来演示行为。 它登录到控制台以证明内部指令适用于内部和外部元素。

https://plnkr.co/edit/3qLt6mzcVkEcYbEHg81s

以我描述的方式可以做到吗? 我应该如何创建可以将指令正确应用于其子项的自定义指令?

我可以通过为指令设置高priority并将terminal设置为true来解决此问题。

  module.directive("inputField", ["$log", function($log) {
    return {
      restrict: "E",
      replace: true,
      priority: 1000,
      terminal: true
      // ... Rest of definintion ...
    }
  }]);

较高的优先级有助于确保首先处理我的input-field指令,并且terminal告诉angular停止编译优先级低于input-field的其余指令。 这使我可以将这些指令的实际处理推迟到将它们转移到适当的子元素之前。

此更新的Plunker显示了正在解决的问题:

https://plnkr.co/edit/NoUwGKn11oc86hbtqTik

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM