ng-transclude that also transcludes scope

With the built-in ng-transclude the the scopes become siblings. What if we want the transcluded HTML to inherit the scope of our directive?

Thanks to Controlling Scope on the Transclude Function on ng-nuggets I was able to figure this out:

    angular
        .module('myApp.myModule')
        .directive('myDirective', myDirective);

    function myDirective() {
        return {
            controller: Controller,
            transclude: true,
            restrict: 'E',
            controllerAs: 'vm',
            link: linkThatTranscludeWithOurScope,
            scope: {}
        };
    }

    function linkThatTranscludeWithOurScope(scope, element, attrs, ctrl, transclude) {
        transclude(scope, function (clone) {
            element.append(clone);
        });
    }

PS. Do not include any template with this directive!

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.