Search code examples
javascriptangularjsangular-directive

AngularJS - Transclude content of nested attribute directive


Is it possible to transclude contents of a nested AngularJS directive which is passed as attribute?

This is the HTML

<div ng-controller="DemoCtrl">
  Hello test.
  <my-directive special/>
</div>

and directives:

var myApp = angular.module('myApp', []);
myApp.controller('DemoCtrl',['$scope', function($scope){

}])
.directive('myDirective', function(){
    return {
        restrict: 'E',
        replace: true,
        scope: {},
        transclude: true,
        template: "<div>Hello, <div ng-transclude></div></div>"
    }

}).directive('special', function(){
    return {
        restrict: 'A',
        template: '<div>Special</div>'

    };

}).directive('special2', function(){
    return {
        restrict: 'A',
        template: '<div>Special2</div>'

    };

});

This is the jsfiddle link https://jsfiddle.net/c8gscx3t/2/

Basically, I would like to have a parent directive, and two child directives, that can via attribute change the content of the parent directive. That way I can put myDirective on the page and control via attribute whether it is special of special2.

Angular noob here, so feel free to suggest a better approach.


Solution

  • You can't have two directives with templates in the same tag, try this:

    <div ng-controller="DemoCtrl">
      <my-directive>
        <special></special>
      </my-directive>
    </div>
    
    var myApp = angular.module('myApp', []);
    myApp.controller('DemoCtrl',['$scope', function($scope){
    
    }])
    .directive('myDirective', function(){
        return {
            restrict: 'E',
            replace: true,
            scope: {},
            transclude: true,
            template: "<div>Hello <div ng-transclude></div></div>"
        }
    
    }).directive('special', function(){
        return {
            restrict: 'AE',
            template: '<div>Special</div>'
    
        };
    
    }).directive('special2', function(){
        return {
            restrict: 'A',
            template: '<div>Special2</div>'
    
        };
    
    });
    

    https://jsfiddle.net/c8gscx3t/3/