Ken Mayer
Ken Mayer

Reputation: 1932

ng-repeat inside an ng-transclude (directive)

Here's the plnkr: http://plnkr.co/HVnZWK5dNuvu180HCT6o

I thought I wrote a simple directive that just rewrites table elements a little. The intent is to let the transcluded body do its thing with respect to the parent scope. It's a toy, I know, but I'm trying to test drive out a "smarter" table, but I can't get past the basics.

daTable.js:

angular.module('daTable', [])
.directive('daTable', function() {
  return {
    restrict: 'E',
    replace: true,
    templateUrl: 'templates/da-table.html',
    transclude: true,
    scope: {}
  }
});

da-table.html:

<table class="table table-bordered table-striped table-hover table-condensed" border="1">
  <caption>Table</caption>
  <thead><tr><th>column 1</th></tr></thead>
  <tbody ng-transclude></tbody>
</table>

main.html (a routed view through the $routeProvider)

...
<da-table>
  <tr ng-repeat="r in rows">
    <td>{{r.col1}}</td>
    <td>{{r.col2}}</td>
    <td>{{r.col3}}</td>
  </tr>
</da-table>
...

main.js:

dataTableApp.controller('MainCtrl', function($scope) {
  $scope.rows = [
    {col1: "data 1,1", col2: "data 1,2", col3: "data 1,3"},
    {col1: "data 2,1", col2: "data 2,2", col3: "data 2,3"},
    {col1: "data 3,1", col2: "data 3,2", col3: "data 3,3"}
  ]
});

Upvotes: 3

Views: 2968

Answers (2)

Nate
Nate

Reputation: 2205

I've been doing a lot of research in the area of directives not working properly with transclusion and ng-repeat.

I came across this: https://github.com/angular/angular.js/issues/1459

Which basically says to avoid using <table>, <td>, or <tr>'s in directives. The problem is that the content is being moved outside of the element by the browser before angular has a chance to even look at them.

They strongly recommend (in the github issue) to use a CSS based table with your directive.

Upvotes: 6

Valentyn Shybanov
Valentyn Shybanov

Reputation: 19391

Actually I think it is really tricky issue and my vote is that this behaviour is because how browsers reorder emelents that are inside elements. It can 'pop' elements that are not inline with what table can contain.

And in your example ngTransclude appends transcluded content after , so order of elements becomes invalid and elements poped out of so are not shown.

So may be try to use other options to structure your page layout - like fluid layouts etc, that allows to avoid wierd browser's behavour with elements.

Upvotes: 0

Related Questions