Switch to Angular directive by placing elements inside one 'span'

Here is my directive:

myapp.directive('envtable', function () { return { restrict: 'E', replace: true, transclude: true, template: '<table class="table" ng-transclude></table>' }; }); 

This is how I use it in html (using bootstrap css)

 <envtable> <tr> <td>OS</td> <td>{{env.osName}}</td> </tr> <tr> <td>OS Version</td> <td>{{env.osVersion}}</td> </tr> </envtable> 

However, the generated code looks like this: chrome:

 <table class="table" ng-transclude=""><span class="ng-scope ng-binding"> OS Windows 8 OS Version 6.2 </span></table> 

As you can see, Angular simply ignored all my tr/td tags and put the content in a single span element. Why is this happening?

Btw, as an experiment, I tried to use only the transcluded p tags in envtable instead of the tr\td tags, in which case Angular just adds the ng-scope class to the p tag. So why does this wrap these tr / td tags?

+7
javascript angularjs angularjs-directive
source share
3 answers

Turns out this works with restrict: 'A'

 <table envtable> <tr> <td>OS</td> <td>{{env.osName}}</td> </tr> <tr> <td>OS Version</td> <td>{{env.osVersion}}</td> </tr> </table> 

Demo

+6
source share

Just provide another example if your table template has other elements like thead

Plunker

 app.directive('envtable', function() { return { replace: true, transclude: true, template: '<table class="NewTable"><thead><th>Col1</th><th>Col2</th><th>Col3</th></thead></table>', link: function(scope, elem, attrs, controller, transcludeFn) { var item = transcludeFn(scope, function(clone) { return clone.children(); }); elem.append(item); } }; }); <table envtable> <tbody> <tr ng-repeat='r in rows'> <td>{{r.col1}}</td> <td>{{r.col2}}</td> <td>{{r.col3}}</td> </tr> </tbody> </table> 
+1
source share

I think this may be a repetition, but your solution is simple. Avoid using <table> !

If you remove the <table> tags, replace them with <div> with the display: table style, it should work fine.

0
source share

All Articles