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

前端 未结 3 1206
不知归路
不知归路 2020-12-08 04:58

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

相关标签:
3条回答
  • 2020-12-08 05:22

    <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

    0 讨论(0)
  • 2020-12-08 05:23

    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.

    0 讨论(0)
  • 2020-12-08 05:26

    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

    0 讨论(0)
提交回复
热议问题