2014-01-07 33 views
4

考慮下面的代碼(http://jsbin.com/IfejIWES/1/):Transclusion(真) - 結合值

HTML:

<!DOCTYPE html> 
<html ng-app="myApp"> 
<head> 
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.3/angular.min.js"></script> 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
</head> 
<body> 
    <div ng-controller="MyCtrl"> 

    <div my-directive> 
     <button>some button</button> 
     <a href="#">and a link</a> 
    </div> 
</div> 
</body> 
</html> 

JS:

var myApp = angular.module('myApp',[]); 

function MyCtrl($scope) { 
    //$scope.log=[]; 
} 

myApp.directive('myDirective', function(){ 
    return{ 
     transclude: true, 
     template: '<div class="something" ng-transclude> This is my directive content</div>' 
    }; 
}); 

使用版本AngularJS的1.1.3,輸出合併了從my-directive(在HTML中)的按鈕和錨點與模板板內文本'這是我的指令內容'。

如果我將版本更改爲1.2.1 my-directive content 將替換模板的內部文本。

有沒有辦法讓角度1.2.1(和更高版本)做更舊的行爲?

回答

1

不,這是一個非常有意的改變。見this commit

0

Jeff Hubbard提供的鏈接(感謝Jeff)讓我朝着正確的方向發展。從該帖子的評論有人(https://github.com/angular/angular.js/commit/eed299a31b5a6dd0363133c5f9271bf33d090c94#commitcomment-4685184)發佈了一項工作:http://plnkr.co/edit/EjO8SpUT91PuXP0RMuJx?p=preview

本質上,您可以通過更改JavaScript以在單獨的指令中使用transcludeFn函數來獲取舊的行爲。請參閱下面我更新的代碼:

var myApp = angular.module('myApp',[]); 

function MyCtrl($scope) { 

} 

myApp.directive('myDirective', function(){ 
    return{ 
     transclude: true, 
     template: '<div class="something" ng-transclude-append> This is my directive content</div>'  
    }; 
}); 

myApp.directive('ngTranscludeAppend', function() { 
    return function(scope, element, attrs, ctrl, transcludeFn) { 
     if (!transcludeFn) return; 

     transcludeFn(function(clone) { 
     element.append(clone); 
     }); 
    }; 
}); 

鏈接到我的更新jsbin:http://jsbin.com/IfejIWES/3/

最後一點,我想在我的鏈接功能直接嵌入transcludeFn這樣的:

link: function(scope, element, attrs, ctrl, transcludeFn) {   
    transcludeFn(function(clone) { 
    element.append(clone); 
    }); 
} 

但這有創建按鈕並錨定兩次的效果。將它轉化爲自己的指令爲我解決了它。