AngularJS directive with ngTransclude not showing {{bound}} content

188 views Asked by At

I'm attempting to create an Angular directive that creates a standardised structure of a table that I wish to use around my application.

I want to specify the structure of the tr when I declare the directive in HTML so that I can have different layouts depending on the data that is passed in. However, I can't seem to get the content of ng-transclude to actually render.

Plunker: Example

I'd like the following:

<custom-table table="data">
  <td>
    {{row.Username}}
  </td>
  <td>
    {{row.FirstName}}
  </td>
  <td>
    {{row.LastName}}
  </td>
</custom-table>

to be injected into the within the template.

How do I get the {{row.Username}} etc tags to resolve within the ng-transclude in the angular directive?

Edit1: I think this is a similar question that I've just found, although most top voted answer seems to recommend avoid using table, tr, td etc within directives :\

2

There are 2 answers

0
Tom On BEST ANSWER

I found a work-around which solves the problem for me.

I've updated the plunker with a working example. I had to create a directive:

app.directive('myTransclude', function() {
    return {
        compile: function(tElement, tAttrs, transclude) {
            return function(scope, iElement, iAttrs) {
                transclude(scope.$new(), function(clone) {
                    iElement.append(clone);
                });
            };
        }
    };
});

I found the issue here within the comments.

I also had to update the directive so it uses a CSS/div based table rather than using an actual HTML table.

1
Joao Leal On

This doesn't answer your question, but I think it is a more generic way of doing what you want.

First pass the list of columns you want to display to your directive:

<custom-table table="data" columns="columns">
</custom-table>

In your controller:

app.controller('MainCtrl', function($scope) {
  $scope.data = [
    {Username: "Test1", FirstName: "Bill", LastName: "Jones"}, 
    {Username: "Test2", FirstName: "Sophie", LastName: "O'Grady"}, 
    {Username: "Test3", FirstName: "Tim", LastName: "Cross"}
    ];

  $scope.columns = ["Username", "FirstName", "LastName"]
});

In your directive:

app.directive('customTable', ['$compile', function($compile){
  return {
    restrict: 'E',
    templateUrl: 'tableTemplate.html',
    scope: {
      table: '=',
      columns: '='
    }
  };
}]);

And finally change your template to:

<div>
  <table>
    <thead>
      <tr>
        <th ng-repeat="col in columns">{{ col }}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="row in table">
        <td ng-repeat="col in columns">
          {{ row[col] }}
        </td>
      </tr>
    </tbody>
  </table>
</div>

And here's the updated plunker: http://plnkr.co/edit/dYwZWD2jB2GsmnvmuSbT