在AngularJS中结合transclude和指令继承

时间:2014-10-16 18:43:28

标签: angularjs

我有这个HTML

<div ng-app="myApp">
    <parent>
        <child></child>
    </parent>
</div>

以及以下Angular代码

var myApp = angular.module('myApp',[]);

myApp.directive('parent', function() {
return {
    transclude: true,
    link: function(scope, element, attrs) {
        scope.getContent = function () {
            console.log('called getContent');
        }
    },
    restrict: 'E',
    template: '<span>parent <span ng-transclude></span></span>'
}
});

myApp.directive('child', function() {
return {
    restrict: 'E',
    scope:true,
    template: '<div>child</div>',
    link: function(scope, element, attrs) {
        scope.getContent();
    }
}
}); 

以上的JSfiddle是here

我在这个例子中的问题是我可以看到继承工作和转换工作是孤立的,但是当我尝试将两者结合起来时,子指令不知道父范围,因此不知道函数getContent。所以没有console.log,在此之前,scope.getContent未定义的子指令错误。

我意识到这可能是因为child指令不再是被转换的孩子所以我认为我需要在编译方法中开始使用post和prelink函数吗?或者我是否需要在父级中定义自定义转换函数?

任何有关代码或进一步阅读的提示都表示赞赏 - 我在这里有关于此类事情的阅读和类似问题,但我发现很难遵循并希望有人可以解决我的问候世界以启动我的理解

提前致谢

2 个答案:

答案 0 :(得分:2)

您应该阅读该文章:http://www.undefinednull.com/2014/07/07/practical-guide-to-prelink-postlink-and-controller-methods-of-angular-directives/

基本上,您的子链接在父级链接之前调用。你想要做的是使用你的父预链接函数,以便定义scope.getContent,因为孩子被链接。

link: {
    pre: function (scope, element, attrs) {
        scope.getContent = function () {
            console.log('called');
        }
    }
}

JSfiddle:http://jsfiddle.net/floribon/gpwasrkz/3/

答案 1 :(得分:2)

在文档中查看"Creating Directives that Communicate"。也许这是你正在努力实现的解决方案。您可以要求父控制器并调用它的功能:

var myApp = angular.module('myApp', []);

myApp.directive('parent', function () {
    return {
        transclude: true,
        controller: function ($scope) {
            this.getContent = function () {
                console.log('called')
            }
        },
        link: function (scope, element, attrs) {},
        restrict: 'E',
        template: '<span>parent <span ng-transclude></span></span>'
    }
});

myApp.directive('child', function () {
    return {
        restrict: 'E',
        scope: true,
        require: '^parent',
        template: '<div>child</div>',
        link: function (scope, element, attrs, ctrl) {
            ctrl.getContent();
        }
    }
});

请参阅this fiddle