简体   繁体   English

如何在子指令模板中访问父指令属性

[英]How to access parent directive attributes inside the child directive template

I have nested simple directives: 我嵌套了简单的指令:

<ep:dropdown type="modern">
    <ep:dropdown:item color="red">Hello</ep:dropdown:item>
    <ep:dropdown:item color="blue">World</ep:dropdown:item>
</ep:dropdown>

Definition of epDropdown directive: 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;
        }
    };
});

And epDropdownItem directive: 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>';
        },
    };
});

I can access the type attribute of parent directive inside the template string. 我可以在template字符串中访问parent指令的type属性。 The problem is I can't access it inside the javascript itself. 问题是我无法在javascript本身内部访问它。 console.log(attr.type) returns undefined . console.log(attr.type)返回undefined How can I access it? 我该如何访问? Here is jsFiddle Demo . 这是jsFiddle演示

This is probably not the cleanest way of solving the given problem, but it works. 这可能不是解决给定问题的最干净的方法,但它可行。 You can navigate to the parent element via jqLite and access the attributes: 您可以通过jqLit​​e导航到父元素并访问属性:

elem.parent().attr("type");

Updated & working: http://jsfiddle.net/D6598/2/ 更新并工作: http : //jsfiddle.net/D6598/2/

If you do a console.log of elem in child, it returns the child element which does not have type property. 如果在child中执行elem的console.log,它将返回不具有type属性的child元素。

But when the child is transcluded in the parent element, which has a type property it get that property value. 但是,当子元素包含在具有类型属性的父元素中时,它将获得该属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM