web_dev web_dev - 2 months ago 11
AngularJS Question

custom directives - child directives do not show up when enclosed within parent directive

Note: ui-grid is name of my custom grid. Sorry about the confusion.

I have a custom directive which will have a child custom directive and will be called in this fashion in the html.

<ui-grid resource="/api/data.json">
<ui-gridcolumns>
</ui-gridcolumns>
</ui-grid>


When the child directive is enclosed within the parent directive, the console statements do not print, but when the child directive is outside of the parent directive, it prints console.log just fine. Any insight into how to make it work with the child directive within the parent directive is appreciated.

parent directive:

module.exports = function () {
return {
restrict: 'E',
templateUrl: 'app/ui-grid/grid.template.html',
link: function (scope, element, attrs) {
console.log('linked Grid');
},
controller: ['$scope', function ($scope) {
$scope.onthescreen = 'test value';
}]
};
};


Child directive:

module.exports = function () {
return {
restrict: 'E',
templateUrl: 'app/ui-grid/gridcolumns/grid.columns.template.html',
link: function (scope, element, attrs) {
console.log('linked Grid Columns');
},
controller: ['$scope', function ($scope) {
console.log('calling Grid Columns');
}]
};
};


The entire code base is in git for reference.

https://github.com/eshrinivasan/angular-gulp-browserify-boilerplate

Answer

To achieve desired behavior use transclusion:

config:

restrict: 'E',
templateUrl: 'app/ui-grid/grid.template.html',
link: function (scope, element, attrs) {
   console.log('linked Grid');
},
controller: ['$scope', function ($scope) {
     $scope.onthescreen = 'test value';   
}],
transclude: true

and somewhere in template:

<div ng-transclude>
   child directives will be placed here
</div>