angularjsangularjs-ng-transclude

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 its 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 run my code, I get the following error: [ngTransclude:orphan].

What should I do? I am using AngularJS v1.5.8


Solution

  • 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)