[英]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.