Search code examples
javascriptangularjsangularjs-componentsangularjs-1.5

AngularJS 1.5 component ng-repeat display as table


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: '='
   }
});

Solution

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