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

时间:2014-06-18 08:29:45

标签: javascript angularjs angularjs-directive angularjs-scope

我有嵌套的简单指令:

<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>';
        },
    };
});

我可以在type字符串中访问parent指令的template属性。 问题是我无法在javascript本身内访问它。 console.log(attr.type)返回undefined如何访问它?这是 jsFiddle Demo

2 个答案:

答案 0 :(得分:1)

这可能不是解决给定问题的最简洁方法,但它确实有效。您可以通过jqLit​​e导航到父元素并访问属性:

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

更新&amp;工作:http://jsfiddle.net/D6598/2/

答案 1 :(得分:0)

如果你在child中执行了 elem 的console.log,它将返回没有type属性的子元素。

但是当子元素被转义为具有 type 属性的父元素时,它会获得该属性值。