Detect if a transclude content has been given for a angularjs directive

前端 未结 4 2152
小鲜肉
小鲜肉 2020-12-10 00:19

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

4条回答
  •  渐次进展
    2020-12-10 01:02

    Here is a plunker: http://plnkr.co/edit/ednJwiceWD5vS0orewKW?p=preview

    You can find the transcluded element inside the linking function and check it's contents:

    Directive:

    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
        }
      }
    })
    

    Template:

    ...

    You can also create your custom transclusion directive like so:

    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);
          })
        }
      }
    })
    

提交回复
热议问题