2013-11-20 129 views
0

我有一個這樣的元素:Angularjs指令模板transclusion

<input test class="foo bar" ng-model="foo" name="foo"/> 

而且我試圖把它變成像下面的例子中,當它具有「測試」屬性:

<div class="something"> 
    <input type="text" class="foo bar" ng-model="foo" name="foo"/> 
    <span>test</span> 
</div> 

但是我有問題transclusion,而不是屬性被轉移到輸入端,他們得到轉移到div,所以我最終的東西,如:

<div class="something foo bar" type="text" ng-model="foo" name="foo"> 
    <input/> 
    <span>test</span> 
</div> 

這裏的指令:

.directive('test', [function() { 
    return { 
     transclude:true, 
     replace:true, 
     template:'<div class="something">\ 
      <input ng-transclude>\ 
      <span>hi</span>\ 
     </div>', 
     link: function (scope, element, attrs, ngModel) { 
      // do stuff 
     } 
    } 
}]) 

回答

0

您將無法transclude這樣:

<input test class="foo bar" ng-model="foo" name="foo"/><!-- NO --> 

我相信你最好的機會(與元素層次的指令)是:

<test> 
    <input class="foo bar" ng-model="foo" name="foo"/> 
</test> 

在這種情況下,該指令的template將爲:

template: 
    '<div class="something">\ 
     <ng-transclude />\ 
     <span>hi</span>\ 
    </div>', 
0

我想你可以試試這個指令:

JS

var app = angular.module('app',[]); 
function myCtrl($scope){ 

} 
app.directive("test",function(){ 
    return { 
    template: '<div class="something"><input type="text" class="foo bar" ng-model="foo" name="foo"/><div ng-transclude></div></div>', 
    transclude: true, 
    replace: true 
    }; 
}); 

HTML

<div test ng-controller="myCtrl"> 
    <span>333</span> 
</div> 

輸出將臨客這樣的:

<div class="something ng-scope" test="" ng-controller="myCtrl"> 
    <input type="text" class="foo bar ng-pristine ng-valid" ng-model="foo" name="foo"> 
    <div ng-transclude=""> 
    <span class="ng-scope">333</span> 
    </div> 
</div> 

jsfiddle demo

希望這有助於您