AngularJS Directives: Using Transclusion Part2

18 February 2014

除了上文中使用的ng-transclude,AngularJS还有其他两种方式可以引用transclude directive的内容:compile方法和directive controller:

myModule.directive('myDirective', function() {
    return {
        transclude: true, // first set transclude to true (or element)
        compile: function(element, attrs, transcludeFn) { ... }; // 1). use transclude in compile function
        controller: function($scope, $transclude) { ... }, // 2). use transclude in directive controller
    };
});

其中在compile阶段引用transclude的方式如下:

compile: function(element, attrs, transcludeFn) {
    return function postLink(scope, element, attrs, controller) {
        var newScope = scope.$parent.$new();
        element.find('p').first().append(transcludeFn(newScope));
    };
}

使用directive controller访问$transclude的方式如下:

controller: function($scope, $element, $transclude) {
    $element.find('p').first().append($transclude());
}

下一篇: 美国自驾攻略 →

blog comments powered by Disqus