2015-09-18 54 views
2

我想创建它本身可以被插入到该模板的指令,像这样:获取指令元素和模板元素都为编译指令

(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> 

我想避免这种情况。

这可能吗?

+0

你为什么要这么做?为什么不从开始就将模板放置在模板中? – sirrocco

+0

正如我所说,我不想添加额外的换行元素,因为我有近50 +填写表单中的字段。 – hguser

+0

那么你仍然会使用父指令(只有模板会有子指令)。所以你仍然会有 sirrocco

回答

1

您可以使用tranclude : 'element'

From angular docs :

“元素” - transclude整个指令的元素,包括 这个元素在一个较低的优先级定义比 该指令的任何指示。使用时,模板属性将被忽略。

a working demo using your exemple

+0

正是我所需要的。谢谢。 – hguser

+0

但是我发现模板的根元素会自动添加指令'class'' ng-model'的所有属性,请检查:http://plnkr.co/edit/icEzd9QUN30KwDlHZ9Wm?p = preview – hguser