AngularJS可选ng-transclude

Far*_*ıcı 19 angularjs angularjs-ng-transclude

我在AngularJS 1.5中编写了一个名为'news'的自定义指令.

它的布局如下:

<div class="row">
    <div class="largeText shadow1" ng-transclude="heading"></div>
    <div class="mediumText shadow2" ng-transclude="content"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

该指令的JavaScript文件如下:

return {           
    restrict: 'E',
    transclude: {
      'heading': 'heading',
      'content': 'content'
    },
    scope: {
        //Some parameters here
    },
    templateUrl: '/directives/news.html'
};
Run Code Online (Sandbox Code Playgroud)

如您所见,我的新闻指令有两个孩子,称为标题和内容字段.它可以使用如下:

<news>
    <heading>
        //Any content goes here
    </heading>
    <content>
        //Any content goes here
    </content>
</news>
Run Code Online (Sandbox Code Playgroud)

到目前为止,该指令运行良好.我的意思是,只要标题和内容部分填充了一些内容,该指令就会按预期显示它们.但是,我试图使这些翻译插槽不是强制性的.每当我使用该指令时:

<news>
    <heading></heading>
</news>
Run Code Online (Sandbox Code Playgroud)

AngularJS抛出一个错误,说我没有填充内容插槽.是否有可能使这些插槽可选?

CSh*_*ark 26

我无法真正找到实际文档中的位置,但基于我看到的示例,我相信您可以?在值之前使用a 来使插槽可选.

例:

transclude: {
  'heading': 'heading',
  'content': '?content'
}
Run Code Online (Sandbox Code Playgroud)

这来自角度文档中的示例,地址为https://docs.angularjs.org/api/ng/directive/ngTransclude#multi-slot-transclusion.它在app.js.

您还可以通过执行以下操作为插槽可选的情况添加默认值:

<div class="largeText shadow1" ng-transclude="heading">Default stuff for the slot goes here</div>
Run Code Online (Sandbox Code Playgroud)


编辑:实际上我在文档中找到了它.它在本节中说https://docs.angularjs.org/api/ng/service/$compile#transclusion:

如果元素选择器带有前缀,?那么该插槽是可选的.例如,transclude对象{ slotA: '?myCustomElement' }将<my-custom-element>元素映射到slotA插槽,可以通过$transclude函数或ngTransclude指令访问它.