2015-09-18 52 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