Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide element if transcluded contents are empty?

I created a very simple directive which displays a key/value pair. I would like to be able to automatically hide the element if the transcluded content is empty (either zero length or just whitespace).

I cannot figure out how to access the content that gets transcluded from within a directive.

app.directive('pair', function($compile) {
  return {
    replace: true,
    restrict: 'E',
    scope: {
      label: '@'
    },
    transclude: true,
    template: "<div><span>{{label}}</span><span ng-transclude></span></div>"
  }
});

For example, I would like the following element to be displayed.

<pair label="My Label">Hi there</pair>

But the next two elements should be hidden because they don't contain any text content.

<pair label="My Label"></pair>
<pair label="My Label"><i></i></pair>

I am new to Angular so there may be a great way handle this sort of thing out of the box. Any help is appreciated.

like image 853
jessegavin Avatar asked Apr 02 '13 15:04

jessegavin


1 Answers

Here's an approach using ng-show on the template and within compile transcludeFn checking if transcluded html has text length.

If no text length ng-show is set to hide

app.directive('pair', function($timeout) {
  return {
    replace: true,
    restrict: 'E',
    scope: {
      label: '@'
    },
    transclude: true,
    template: "<div ng-show='1'><span>{{label}} </span><span ng-transclude></span></div>",
    compile: function(elem, attrs, transcludeFn) {
            transcludeFn(elem, function(clone) { 
              /* clone is element containing html that will be transcludded*/
               var show=clone.text().length?'1':'0'
                attrs.ngShow=show;
            });
        }
  }
});

Plunker demo

like image 180
charlietfl Avatar answered Nov 09 '22 20:11

charlietfl