1

问题:给定一个包含“n”个项目的数组,我希望它们分别呈现在 m 行的单独表中。例如,如果我有一个 n=30 项且 m=6 的数组,那么我需要 5 个包含 6 个项的表,每个表水平堆叠在一起。

尝试的解决方案:我尝试使用 ng-repeat 和 ng-switch 来渲染一些东西来达到这种效果,但它没有用。我能够将这些项目呈现为一个表(这很简单)。

我知道下面粘贴的代码不起作用,因为第一个 ng-switch 没有关闭 and 标签。是否有任何众所周知的技巧来实现这样的目标?

itemapp.directive("items", function () {
    'use strict';

    return {
        restrict: 'E',
        template: '<div id="itemDiv" ng-repeat="item in items" ng-show="$index==0">' +
            '<span ng-switch on="$index % 10">' +
            '   <div ng-switch-when="0">' +
            '           <table><tbody>'+
            '   </div>'+
            '<tr class="itemon">' +
            '<td><input type="radio" ng-model="item.on" value="0" >OFF</input></td>' +
            '<td>{{$index}}</td>'+
            '</tr>' +
            '   <div ng-switch-when="9">' +
            '    </table></tbody>'+
            '   </div>'+
            '</span>' +
            '</div  ng-show="$index==0">',
        link: function (scope) {

        },
        scope: {
            items: '='
        }
    };
});

这是作为 HTML 模板的代码:

<div id="itemDiv" ng-repeat="item in items" ng-show="$index==0">
 <span ng-switch on="$index % 10">
<div ng-switch-when="0">
    <table>
        <tbody>
</div>
           <tr class="itemon">
               <td><input type="radio" ng-model="item.on" value="0">OFF</input></td>
               <td>{{$index}}</td>
            </tr>
      <div ng-switch-when="9">
          </table></tbody>
      </div>
</span>
</div  ng-show="$index==0">
4

1 回答 1

3

就是这样,我解决了它:

指示:

<table ng-repeat='t in getIndexes(tableCount) track by $index'>
  <tbody>
    <tr ng-repeat='item in items' ng-if='isVisible($parent.$index,$index)'>
      <td>{{item.name}}</td>
      <td>{{item.city}}</td>
    </tr>
  </tbody>
</table>

getIndexes - 函数,它只是创建数组,因为 ng-repeat 不能只做简单的重复,只能做一个聪明的重复。

isVisible - 函数,它根据源数组中的位置定义适当 tr 的可见性。

指令代码:

app.directive("tconstructor", function () {
    'use strict';

    return {
        restrict: 'AE',
        templateUrl: 'directive.html',
        scope: {
            items: '=',
            perTable: '=' // items per table
        },
        link: function ($scope, $element, attrs) {
              $scope.tableCount = $scope.items.length / $scope.perTable;
              $scope.getIndexes = function(count) {
                return new Array(count);
              },

              $scope.isVisible = function(t,i) {
                console.log(t,i,(t*$scope.perTable <= i), (i < (t+1)*$scope.perTable) );
                return (t*$scope.perTable <= i) && (i < (t+1)*$scope.perTable);
              }
        }

    };
});

索引页:

 <div ng-controller="SimpleController">
  <tconstructor items='items' per-Table='perTable'></tconstructor>
 </div>

实时代码:我已将项目数组设置为 8 个元素,并且每个表计数 = 2,结果是 4 个表,每个表有 2 个元素。

http://plnkr.co/edit/eUM7UJap3VIYvi0dMMbc?p=preview

应该没有问题,可以调整代码并达到您的目标。希望有帮助

于 2014-02-13T23:14:06.783 回答