rastemoh rastemoh - 3 months ago 23
AngularJS Question

Nested and slotted Transclude in AngularJS

I have an element which its whole content could be transcluded. the transclusion is optional, so I can let it's inner parts stay but an inner element be transcluded. let's see it in action:

<h4 class="modal-title" ng-transclude="title">
Are you sure you want to remove this <span ng-transclude="innerType">good</span>
</h4>


in directive definition I have:

myApp.directive('confirmDeleteModal',function(){
return {
restrict:'E',
transclude:{
title:'?modalTitle',
innerType:'?modalType',
},
templateUrl:'templates/confirm_delete_modal.html',
scope:{
obj:'=info',
},
}
});


The HTML code would be so:

<confirm-delete-modal info="goodToBeDeleted">
<modal-type>good</modal-type>
</confirm-delete-modal>


When I try this this comes out: Error: [ngTransclude:orphan].
What should I do?
I am using AngularJS v1.5.8

Answer

You use another directive ng-transclude in a fall back content of modal-title. But the ng-transclude become the "parent" of the span and doesn't provide transclusion function. I suggest to you to modify your directive and to use the method isSlotFilled to know if title is filled or not :

directive('confirmDeleteModal',function(){
return {
  restrict:'E',
  transclude: {
    title:'?modalTitle',
    innerType:'?modalType',
  },
  link: function(scope, elem, attrs, ctrl, trfn) {
    scope.titleFilled = trfn.isSlotFilled('title');
  },
  template:'<h4 class="modal-title" ng-transclude="title" ng-if="titleFilled"></h4>' +
           '<h4 class="modal-title" ng-if="!titleFilled">Are you sure you want to remove this <span ng-transclude="innerType">good</span></h4>',
  scope:{
      obj:'=info',
  }
 }
})

(https://plnkr.co/edit/k0RXLWbOvHdNc9WFpslz?p=preview)

Comments