Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

directive not working inside <tr> that is ng-repeat bound

I have a table where the rows are repeated via ng-repeat. I am trying to create a template that generates columns <td> for each row <tr>

app.directive("customtd", function(){
  return {
    restrict: 'E',
    template: "<td>{{position.Name}}</td><td>{{position.Code}}</td>",
    replace: true,
    scope: {
      position: '='
    }
  }
});
<table>
  <tr ng-repeat="p in positions">
    <customtd position="p"></customtd>
  </tr>
</table>

The issue is my custom td template is not rendered at all. Here I intend to replace <customtd> with n number of <td>s - which will be decided based on number of properties on my data object, but at the moment I am just trying to get a simple directive working that will output two columns.

MYPLUNKER : shows an instance of this issue and the directive code.

like image 358
dotnetcoder Avatar asked Aug 25 '13 06:08

dotnetcoder


2 Answers

As pointed out in comments the template of a directive should have single root element. So I would suggest you to move the tr element to the template of the directive, like this: http://plnkr.co/edit/YjLEDSGVipuKTqC2i4Ng?p=preview

like image 108
Pavlo Avatar answered Oct 23 '22 05:10

Pavlo


As Pavlo wrote, you can move the tr element to the template for the directive. Another option is to use a td element and directive that replaces your td with the template that you want to use.

<table>
  <tr ng-repeat="p in positions">
    <td replace-me template="mytemplate.html" position="p"></td>
  </tr>
</table>

Directive replaceMe

.directive("replaceMe", ["$compile", '$http', '$templateCache', function ($compile, $http, $templateCache) {
        return {
            restrict: 'A',
            scope: {
               position: "="
            },
            link: function (scope, element, attrs) {
                function getTemplate(template) {
                    $http.get(template, {cache: $templateCache}).success(function (templateContent) {
                        element.replaceWith($compile(templateContent)(scope));
                    });
                }
                scope.$watch(attrs.template, function () {
                    if (attrs.template) {
                        getTemplate(attrs.template);
                    }
                });


            }
        }
    }]);

mytemplate.html

<td>{{position.Name}}</td>
<td>{{position.Code}}</td>
<td another-my-directive></td>

plunker

like image 43
szapio Avatar answered Oct 23 '22 06:10

szapio