[英]How to access parent directive attributes inside the child directive template
我嵌套了簡單的指令:
<ep:dropdown type="modern">
<ep:dropdown:item color="red">Hello</ep:dropdown:item>
<ep:dropdown:item color="blue">World</ep:dropdown:item>
</ep:dropdown>
epDropdown
指令的定義:
app.directive('epDropdown', function () {
return {
scope: {type: '@'},
restrict: "E",
replace: true,
transclude: true,
template: function (elem, attr) {
var template;
if (attr.type == 'modern') {
template = '<div ng-transclude></div>';
}
return template;
},
controller: function($scope) {
this.type = $scope.type;
}
};
});
和epDropdownItem
指令:
app.directive('epDropdownItem', function () {
return {
require: '^epDropdown',
restrict: "E",
replace: true,
transclude: true,
scope: { color: '@' },
link: function (scope,element,attrs,parentCtrl){
scope.type = parentCtrl.type;
},
template: function (elem, attr) {
var template = '';
console.log(attr.color);
console.log(attr.type); // undefined -> how to access `type` attr of parent
return '<div>PARENT type: {{ type }} | CHILD color: {{ color }}</div>';
},
};
});
我可以在template
字符串中訪問parent指令的type
屬性。 問題是我無法在javascript本身內部訪問它。 console.log(attr.type)
返回undefined
。 我該如何訪問? 這是jsFiddle演示 。
這可能不是解決給定問題的最干凈的方法,但它可行。 您可以通過jqLite導航到父元素並訪問屬性:
elem.parent().attr("type");
更新並工作: http : //jsfiddle.net/D6598/2/
如果在child中執行elem的console.log,它將返回不具有type屬性的child元素。
但是,當子元素包含在具有類型屬性的父元素中時,它將獲得該屬性值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.