[英]AngularJS : Bind to transclusive directive without isolating the scope
假設我有一些角度標記,例如:
<custom bindTo="modelProperty">
<!-- Trascluded content. -->
</custom>
custom指令是否可以使用bindTo屬性進行綁定,從而允許所包含的內容可以訪問這些屬性,而無需隔離custom的范圍? 基本上,我希望一個指令綁定到該模型的自定義部分,而不會使其脫離父級范圍,也不必添加諸如以下的額外代碼:
scope.prop = scope.$parent.prop;
有任何想法嗎?
編輯我想它的結構類似於http://plnkr.co/edit/zq2OO1?p=preview ,除了可以工作並且沒有隔離范圍。
通過使用scope: true
您可以通過原型繼承來維護對父范圍的屬性的訪問,同時為指令的每個實例維護唯一的范圍(即,使其可重用)。 (注意:請確保您要遵循的點規則是您需要從被包含的內容中在父范圍上更改的任何模型的原因)
您需要從compile
函數中調用transclude
函數,並將指令的范圍作為第一個參數傳遞,以便將被包含的內容與其鏈接起來。
它可能看起來像這樣:
.directive('custom', function() {
return {
restrict: 'E',
transclude: true,
scope: true,
link: function(scope, elem, attrs, ctrl, transclude){
scope.bindTo = scope[attrs.bindTo];
transclude(scope, function(clone){
elem.find('ng-transclude').replaceWith(clone);
});
},
template: '<div>From parent scope: <i>{{someVar}}</i> <ng-transclude></ng-transclude></div>'
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.