AngularJS ng-repeat with custom element inside a table is rendering strangely

倖福魔咒の 提交于 2019-11-28 04:56:10

<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>

Live Demo

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

boneskull

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!