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

Seb*_*ian 40 angularjs angularjs-directive

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

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

所以我想补充一下:

<div class="progress" ng-class="{withLabel: *CODE GOES HERE*}">
    <div class="label"><span ng-transclude></span>
    <div class="other">...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

非常感谢!

Ser*_*eev 59

在使用多插槽转换发布Angular v1.5后,它甚至更简单.例如,您已使用component而不是或directive没有访问权限linkcompile功能.但您可以获得$transclude服务.因此,您可以使用"官方"方法检查内容的存在:

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

使用这样的模板:

<div class="progress" ng-class="{'with-label': withLabel}">
    <div class="label"><span ng-transclude="slot"></span>
    <div class="other">...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

  • 这在使用多插槽功能时很有效.但是如果我只是在组件上使用`transclude:true`设置并想知道是否提供了任何内容呢? (7认同)
  • 不应该是ng-class:`ng-class ="{'with-label':transcludePresent}"`? (4认同)

plo*_*ng0 21

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

$transclude(function(clone){
    if(clone.length){
        scope.hasTranscluded = true;
    }
});
Run Code Online (Sandbox Code Playgroud)

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


Ila*_*mer 9

这是一个吸烟者: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
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

模板:

<div class="progress" ng-class="{'with-label': withLabel}">
    <div class="label"><span ng-transclude></span>
    <div class="other">...</div>
</div>
Run Code Online (Sandbox Code Playgroud)

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

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);
      })
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

  • llan,你有一些注释掉的代码,在什么情况下这是真的?clone.length> 0,我测试过,它总是1 (2认同)