检测是否已为angularjs指令指定了转录内容

问题描述 投票:39回答:4

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

有没有人知道我如何根据是否给出了一个转录内容来为我的指令添加一个类?

所以我想补充一下:

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

非常感谢!

angularjs angularjs-directive
4个回答
56
投票

在使用多插槽转换发布Angular v1.5后,它甚至更简单。例如,您使用component而不是directive,并且无法访问linkcompile函数。但您可以使用$transclude服务。因此,您可以使用“官方”方法检查内容的存在:

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

使用这样的模板:

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

20
投票

基于@ Ilan的解决方案,您可以使用这个简单的$ transclude函数来了解是否存在被转换的内容。

$transclude(function(clone){
    if(clone.length){
        scope.hasTranscluded = true;
    }
});

Plnkr使用ng-if来演示这种方法,如果没有任何内容可以设置默认内容:http://plnkr.co/hHr0aoSktqZYKoiFMzE6


8
投票

这是一个plunker:http://plnkr.co/edit/ednJwiceWD5vS0orewKW?p=preview

你可以在链接函数中找到transcluded元素并检查它的内容:

指示:

app.directive('progressbar', function(){
  return {
    scope: {},
    transclude: true,
    templateUrl: "progressbar.html",
    link: function(scope,elm){
      var transcluded = elm.find('span').contents();
      scope.withLabel = transcluded.length > 0; // true or false
    }
  }
})

模板:

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

您也可以像这样创建自定义转换指令:

app.directive('myTransclude', function(){

  return {
    link: function(scope, elm, attrs, ctrl, $transclude){
      $transclude(function(clone){

        // Do something with this:
        // if(clone.length > 0) ...

        elm.empty();
        elm.append(clone);
      })
    }
  }
})

-1
投票

基于@ plong0和@Ilan的解决方案,这看起来好一点,因为它也适用于空白。

$transcludeFn(function(clonedElement) {
    scope.hasTranscludedContent = clonedElement.html().trim() === "";
});

之前<my-directive> </my-directive>会返回它有.length1,因为它包含一个文本节点。因为传递给$transcludeFn的函数返回了一个jQuery对象的transcluded内容的内容,我们可以只获取内部文本,删除末尾的空格,并检查它是否为空白。

请注意,这只会检查文本,因此包含没有文本的html元素也会被标记为空。像这样:<my-directive> <span> </span> </my-directive> - 这虽然适合我的需要。

© www.soinside.com 2019 - 2024. All rights reserved.