directive not working inside <tr> that is ng-repeat bound
Solution 1
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
Solution 2
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>
Related videos on Youtube
dotnetcoder
Updated on September 16, 2022Comments
-
dotnetcoder over 1 year
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.
-
Arun P Johny over 10 yearsif you look at the console it is throwing an error saying
Template must have exactly one root element. was: <td>{{position.Name}}</td><td>{{position.Code}}</td>
-
-
dotnetcoder over 10 yearsthanks that worked I was kind of disappointed to see the directives with type 'Element' nested in ng-repeat do not make much use. your solution worked. I extended it to display headers by looking the keys on data object. plnkr.co/edit/BEi7an1yhvc4pMgRNTAt?p=preview