1

How to display ng-repeat in a component as a table? Why is my item component not displaying data as table rows?

Here's a Plunker and the code as well:

index.html

<body ng-controller="MainCtrl as vm">
    <table border="1">
        <tbody>
            <item data="name" ng-repeat="name in vm.names"></item>
        </tbody>
    </table>
</body>

item.html

<tr>
  <td>{{$ctrl.data.first}}</td>
  <td>{{$ctrl.data.family}}</td>
</tr>

app.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  var vm = this;
  vm.names = [{family: "dela cruz", first: "juan"}, {family: "tamad", first: "juan"}]
});

angular.module('plunker').component('item', {
   templateUrl: 'item.html',
   bindings: {
     data: '='
   }
});
basagabi
  • 4,900
  • 6
  • 38
  • 84

1 Answers1

2

Remember that the element is kept within the table and tends to break standard HTML table -> tbody -> tr -> td structure.

For this particular case, I would do the following:

angular
  .module('sampleApp', [])
  .controller('MainCtrl', function() {
    var vm = this;
    vm.names = [{family: "dela cruz", first: "juan"}, {family: "tamad", first: "juan"}];
  })
  .component('nameTable', {
     template: [
      '<table border="1">',
      '<tbody>',
      '<tr ng-repeat="name in $ctrl.data">',
      '<td>{{name.first}}</td>',
      '<td>{{name.family}}</td>',
      '</tr>',
      '</tbody>',
      '</table>'
     ].join(''),
     bindings: {
       data: '<'
     }
  });
<body ng-app="sampleApp" ng-controller="MainCtrl as vm">
  <name-table data="vm.names" ></name-table>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js"></script>
</body>
Gorka Hernandez
  • 3,890
  • 23
  • 29
  • Instead of hard-coded html on the `template`, I created an `item.html` and dump the html codes there. It works now! Thanks! – basagabi Mar 02 '17 at 10:20