AngularJS中的嵌套和插槽Transclude

时间:2016-08-11 07:38:58

标签: angularjs angularjs-ng-transclude

我有一个元素,其整个内容可以被转换。转换是可选的,所以我可以让它的内部部分保留但内部元素被转换。让我们看看它的实际效果:

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

在指令定义中我有:

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

HTML代码就是这样:

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

当我运行代码时,出现以下错误:[ngTransclude:orphan]

我该怎么办? 我正在使用AngularJS v1.5.8

1 个答案:

答案 0 :(得分:1)

您在模态标题的后备内容中使用另一个指令ng-transclude。但是ng-transclude成为了#34;父母&#34;跨度,并没有提供翻译功能。我建议你修改你的指令并使用方法isSlotFilled来知道标题是否被填充:

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