I\'m trying to re-use a portion of my HTML view in multiple places. The portion I want to re-use is table cells in an HTML table. The problem is that my custom directive i
<td>
is known to behave strangely in directives like this. Instead, use a directive on the parent <tr>
. Read more about this issue here: https://github.com/angular/angular.js/issues/1459
<table>
<tr ng-repeat="p in people" my-element></tr>
</table>
Here is how you can further improve your directive so that it is more re-usable.
app.directive('myElement', function () {
return {
scope: {
item: '=myElement'
},
restrict: 'EA',
template: '<td>Name: {{item.name}}</td><td>Age: {{item.age}}</td>'
};
});
and pass in the value of item
like so:
<table>
<tr ng-repeat="person in people" my-element="person"></tr>
</table>
Use replace: true
in your directive and your <my-element>
will be replaced with the root item in your template, a <td>
, so this will not confuse the HTML.
Apply the directive to <tr>
like this:
<table class="table table-hover">
<tr my-element blah='p' ng-repeat="p in people"></tr>
</table>
app.directive('myElement', function () {
return {
restrict: 'A',
scope:{
ngModel: '=blah'
},
template: '<td>Name: {{ ngModel.name }}</td><td>Age: {{ ngModel.age }}</td>'
}
});
Working Demo