检测是否为 angularjs 指令提供了嵌入内容 [英] Detect if a transclude content has been given for a angularjs directive

查看:17
本文介绍了检测是否为 angularjs 指令提供了嵌入内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令(进度条),它应该有两种可能的状态,一种没有任何描述,另一种在左侧带有标签.简单地使用此标签的嵌入内容会很酷.

有谁知道如何根据是否提供了嵌入内容将类添加到我的指令中?

所以我想补充:

<div class="label"><span ng-transclude></span><div class="other">...</div>

非常感谢!

解决方案

在 Angular v1.5 发布后,多槽嵌入变得更加简单.例如,您使用了 component 而不是 directive 并且无权访问 linkcompile 函数.但是您可以访问 $transclude 服务.因此,您可以使用官方"方法检查内容是否存在:

app.component('myTransclude', {转置:{'slot': '?transcludeSlot'},控制器:函数($transclude){this.transcludePresent = function() {返回 $transclude.isSlotFilled('slot');};}})

使用这样的模板:

<div class="label"><span ng-transclude="slot"></span><div class="other">...</div>

I have a directive (a progressbar) which should have two possible states, one without any description and one with a label on the left side. It would be cool to simple use the transcluded content for this label.

Does anyone know how I can add a class to my directive depending whether a transclude content has been given or not?

So I want to add:

<div class="progress" ng-class="{withLabel: *CODE GOES HERE*}">
    <div class="label"><span ng-transclude></span>
    <div class="other">...</div>
</div>

Thanks a lot!

解决方案

After release of Angular v1.5 with multi-slot transclusion it's even simpler. For example you have used component instead of directive and don't have access to link or compile functions. Yet you have access to $transclude service. So you can check presence of content with 'official' method:

app.component('myTransclude', {
  transclude: {
    'slot': '?transcludeSlot'
  },
  controller: function ($transclude) {
    this.transcludePresent = function() {
      return $transclude.isSlotFilled('slot');
    };
  }
})

with template like this:

<div class="progress" ng-class="{'with-label': withLabel}">
    <div class="label"><span ng-transclude="slot"></span>
    <div class="other">...</div>
</div>

这篇关于检测是否为 angularjs 指令提供了嵌入内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆