angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

Directive fails to insert/replace html when template root element is table row (tr)

Open phaas opened this issue 14 years ago • 69 comments

In an attempt to automate some common table layouts I created a directive that emits the <tr> ...</tr>, including the table cells.

When this directive is applied, angular throws an exception indicating that the template does not have a single root element (it does).

When replace is set to false, this issue does not occur -- but the resulting markup will be invalid.

I suspect that the problem is partially due to the browser "cleaning up" the table HTML and moving unrelated or unknown tags outside of the table -- while preventing table tags from being inserted/replaced at the desired location.

Example

Url: http://jsfiddle.net/phaas/sL9gM/

<div ng-app="tables">
    <table>
        <row key="x" value="y"></row>
        <row key="1" value="2"></row>
        <row key="longer" value="very long!"></row>
    </table>
</div>
angular.module('tables',[])
    .directive('row', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: { key: '@', value: '@' },
            template: '<tr><td>{{key}}</td><td>{{value}}</td></tr>'            
        }
    });

Stack Trace

Error: Template must have exactly one root element. was: <tr><td>{{key}}</td><td>{{value}}</td></tr>
    at applyDirectivesToNode (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:4010:21)
    at compileNodes (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:3790:14)
    at compileNodes (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:3795:14)
    at compile (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:3735:29)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:932:9
    at Object.Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:7808:28)
    at Object.Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:7888:23)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:930:13
    at Object.invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:2788:25)
    at bootstrap (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js:928:12) 

phaas avatar Oct 14 '12 23:10 phaas

Workaround: Instead of replacing a non-standard element with a tr defined in the template, the directive can be applied as an attribute on an existing tr. This avoids the exception but isn't quite as nice to read.

<div ng-app="tables">
    <table>
        <tr row key="x" value="y"></tr>
        <tr row key="1" value="2"></tr>
        <tr row key="longer" value="very long!"></tr>
    </table>
</div>​
angular.module('tables',[])
    .directive('row', function() {
        return {
            restrict: 'A',
            replace: false,
            scope: { key: '@', value: '@' },
            template: '<td>{{key}}</td><td>{{value}}</td>'            
        }
    });​

Edit: Further testing shows that this still breaks ng-transclude:

<div ng-app="tables">
    <table>
        <tr row key="Label 1"><input type="text"></input></tr>
        <tr row key="Label 2">Text</tr>
    </table>
</div>​
angular.module('tables',[])
    .directive('row', function() {
        return {
            transclude: true,
            scope: { key: '@' },
            template: '<td>{{key}}</td><td> <span ng-transclude></span>{{value}}</td>'            
        }
    });​

It appears that the browser is again moving the element content outside of the element before angular has a chance to apply the template. I'm not sure that it's even possible for angular to make this work.

Avoiding table/tr/td entirely and instead using a css-based approach may be the only feasible option here.

phaas avatar Oct 14 '12 23:10 phaas

I'll write this one off to the browser modifying the markup (moving nodes out of the table) before it ever gets to angular.

I rewrote the page & directive using divs with display: table.. styling applied and it works fine.

phaas avatar Oct 15 '12 03:10 phaas

I have the same problem trying to transclude td into a tr.

Please see http://jsbin.com/otogih/9.

marco-m-alves avatar Feb 08 '13 21:02 marco-m-alves

And how about using this solution to ensure transclusion of content which otherwise would be removed by the browser --- if that's the case:

< directive-that-transcludes-content > < script id="transclude-1" type="text/ng-transclude"> < !-- insert content here -- > < /script > < /directive-that-transcludes-content >

Angular would have to try to detect if it is transcluding a script element and then extract the html template from the script and insert it in each element.

Note: I think the id attribute in the script tag is not required

marco-m-alves avatar Feb 08 '13 21:02 marco-m-alves

Working solution here: http://jsbin.com/otogih/18/edit

It uses a scriptTransclude directive.

marco-m-alves avatar Feb 11 '13 12:02 marco-m-alves

Re-opening, as I think this is still an issue.

Here's very simple example of the problem http://jsfiddle.net/A2FPR/2/

vojtajina avatar Feb 14 '13 19:02 vojtajina

Here is a simpler example comparing the scriptTransclude directive and the regular ng-transclude.

It is not directly applicable to the example Vojta has shared but has similarities.

http://jsbin.com/uhocep/2/edit

marco-m-alves avatar Feb 14 '13 21:02 marco-m-alves

I have also run into this problem trying to replace a element with in a directive with the following template:

    ...
    replace:true,
    transclude:true,
    template: '<td ng-transclude></td>

I have a potential fix for the problem. In the file "src/ng/compile.js" line 660 it does this:

    if (directive.replace) {
            $template = jqLite('<div>' +
                                 trim(directiveValue) +
                               '</div>').contents();
            compileNode = $template[0];
            if ($template.length != 1 || compileNode.nodeType !== 1) {
              throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
            }

That is the exception that is thrown, the jqLite calls is failing because it is wrapping the td/tr with in a div the jqLite node creator thinks it's bad HTML. This is the fix I made to make work:

    if (directive.replace) {
            var trimDirective = trim(directiveValue);
            if (trimDirective.substring(0, 3) == '<tr') {
                trimDirective = '<tbody>' + trimDirective + '</tbody>';
            } else if (trimDirective.substring(0, 3) == '<td') {
                trimDirective = '<tr>' + trimDirective + '</tr>';
            } else {
                trimDirective = '<div>' + trimDirective + '</div>';
            }
            $template = jqLite(trimDirective).contents();
            compileNode = $template[0];

rwlogel avatar Feb 27 '13 15:02 rwlogel

Is this planned to be fixed at some point ? I'm happy to look into it if no one's working on it.

stevedomin avatar Jun 27 '13 14:06 stevedomin

vote +1

arturgspb avatar Jul 16 '13 20:07 arturgspb

+1

The work around I've gone with for this problem is naive, but workable for my situation: A linking function to swap out the tag name...

directive("wsReplaceTag", function() {
  return function(scope, element, attrs) {
      var newTag = attrs.wsReplaceTag;
      var nodeAttributes = {};

      $.each(element[0].attributes, function(idx, attr) {
          nodeAttributes[attr.nodeName] = attr.nodeValue;
      });

      element.replaceWith(function () {
          return $("<" + newTag + "/>", nodeAttributes).append(element.contents());
      });
  };
});

And then some monkey business in the template that looks like this (ws-lister is creating a table that ends up with a <tr ng-transclude> element)...

<div ws-lister>

  <div ws-replace-tag="td">
    Name: {{item.name}}
  </div>

  <div ws-replace-tag="td">
    Email: {{item.email}}
  </div>

</div>

davidells avatar Aug 01 '13 22:08 davidells

+1

rweng avatar Aug 05 '13 11:08 rweng

I have encountered the same issue in 1.15.

As suggested, I had to replace the "replace: true" approach by using an attribute tag instead. This worked.

<tr my-row></tr>

pauljoey avatar Aug 15 '13 18:08 pauljoey

Yep, running into this problem right now. I've tried both writing the directive as an element as well as an attribute.

EverybodyKurts avatar Aug 16 '13 04:08 EverybodyKurts

I just managed to fix this for <tr> tags, special cases will be needed for at least thead, tbody, tfoot, th, td too, since none of those can be wrapped in a div.

I will continue work on this tomorrow and hopefully have a working pull request ready that covers all those tags.

pelme avatar Aug 17 '13 14:08 pelme

Any idea if/when pelme's PR will be merged?

bcronje avatar Oct 15 '13 08:10 bcronje

Stumbled about this today too, d'oh! Took me a while to understand that it wasn't my fault but instead a limitation of angular.

marcorinck avatar Nov 03 '13 16:11 marcorinck

Looking forward to an update on this...

Holokai avatar Nov 08 '13 06:11 Holokai

+1

ooflorent avatar Nov 14 '13 13:11 ooflorent

I got around this by doing <div><tr>...</tr></div>. Ugly ugly ugly but it works.

EverybodyKurts avatar Nov 14 '13 13:11 EverybodyKurts