Search code examples
angularjsangularjs-directivehtml-tabledocument-bodyangular-template

Angular directive doesn't work on table


I have the following table:

<table>
  <thead>
    <tr>
      <th>Uno</th>
      <th>Dos</th>
    </tr>
  </thead>

  <!--directive template should be here-->
  <double-rows></double-rows>
  <!--/directive template should be here-->

</table>

The directive is defined as:

angular.module('app', []);

angular.module('app').directive('doubleRows', function () {
  return {
    templateUrl: 'template.html',
    restrict: 'E',
    scope: {
      row: '='
    }
  }
});

As simple as it looks, it doesn't render properly. e.g:

<double-rows class="ng-isolate-scope">

Cell1
Cell2

</double-rows>

<table>
  <thead>
    <tr>
      <th>Uno</th>
      <th>Dos</th>
    </tr>
  </thead>

  <!--directive template should be here-->

  <!--/directive template should be here-->

</table>

You can see the full code in here: https://plnkr.co/edit/0Z65aK?p=preview

How to make it work?


Solution

  • This isn't exactly an angular problem but more to do with how the browser decides to interpret the HTML you wrote. Certain tags aren't allowed to be nested in other tags, this is particularly prevalent within lists (ul, or li) and tables (also applies to nested links and a few other things).

    Instead of using restrict E if you use restrict A and use an element type that is allowed in the table then it works (I also used replace:true on your directive so it replaces the original element it's applied to instead of being a child of it)

    https://plnkr.co/edit/fgRzZU?p=preview

    angular.module('app').directive('doubleRows', function () {
      return {
        templateUrl: 'template.html',
        restrict: 'A',
        replace:true,
        scope: {
          row: '='
        },
        controller: function () {
          console.log('hi');
        }
      }
    });
    

    The HTML

    <table>
      <thead>
        <tr>
          <th>Uno</th>
          <th>Dos</th>
        </tr>
      </thead>
    
      <!--directive template should be here-->
      <tbody double-rows>
      </tbody>
      <!--/directive template should be here-->
    
    </table>