获取指令元素和模板元素以用于编译指令

时间:2015-09-18 01:15:49

标签: angularjs angularjs-directive

我想创建一个可以插入到模板中的指令,如下所示:

(function() {
  function FormInputDirective() {
    return {
      replace: true,
      scope: {
        label: "@"
      },
      compile: function(tElement, tAttrs) {
        //tElement.find(".input-container").append(directiveElement);

        var link = function($scope, element, attrs) {
          //....
        };
        return link;
      },
      templateUrl: 'form-input.html'
    }
  }
  angular.module("mainApp", []).directive("formInput", [FormInputDirective]);
})();

模板:

<div class="form-group input-container">
    <label>{{label}}</label>
    <!-- where the directive element to be inserted -->
</div>

用法:

<input type="number" ... form-input label="Name:" />
<input type="text" ....  form-input label="address:" min-length=... />
<textrea ................form-input label="Description" .......
....

预期结果:

<div class="form-group input-container">
    <label>Name</label>
    <input type="number" ... form-input label="Name:" />
</div>
<div class="form-group input-container">
    <label>Name</label>
    <input type="text" ... form-input label="Address:" />
</div>

.................. Live demo

但是,如果我想让它发挥作用,我将不得不同时获得我不知道的directive elementtemplate element。因为一旦指令有template,那么传递给compile函数的第一个参数将是template element, I can not find a way to get the指令元素。

而且我也知道我可以使用ng-tranclude,但是我必须写出这样的额外元素:

<any-dir>
   <input ...... />
</any-dir>

我想避免这种情况。

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用tranclude : 'element'

From angular docs :

  

'element' - 转换整个指令的元素,包括   对此元素的任何指令,其优先级低于   这个指令。使用时,将忽略template属性。

a working demo using your exemple