AngularJS 1.5组件ng-repeat显示为表格

时间:2017-03-02 09:51:21

标签: javascript angularjs angularjs-components angularjs-1.5

如何在组件中显示ng-repeat作为表格?为什么我的item组件没有将数据显示为表行?

这是一个Plunker和代码:

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

1 个答案:

答案 0 :(得分:1)

请记住,元素保留在表格中,并且往往会破坏标准HTML表格 - &gt; tbody - &gt; tr - &gt; td结构。

对于这种特殊情况,我会做以下事情:

&#13;
&#13;
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: '<'
     }
  });
&#13;
<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>
&#13;
&#13;
&#13;