user2480690
user2480690

Reputation: 155

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:

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:

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. The problem is I can't access it inside the javascript itself. console.log(attr.type) returns undefined. How can I access it? Here is jsFiddle Demo.

Upvotes: 1

Views: 1216

Answers (2)

Himmet Avsar
Himmet Avsar

Reputation: 1531

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:

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

Updated & working: http://jsfiddle.net/D6598/2/

Upvotes: 1

Anand
Anand

Reputation: 14915

If you do a console.log of elem in child, it returns the child element which does not have type property.

But when the child is transcluded in the parent element, which has a type property it get that property value.

Upvotes: 0

Related Questions