如何处理固定列表

时间:2015-08-10 14:22:52

标签: javascript angularjs breeze

我的表格看起来像这样:

<table>
<thead>
    <tr>
        <th>Entry</th>
        <th>1</th>
        <th>2</th>
        <th>3</th>
    </tr>    
</thead>
<tbody>
    <tr>
        <td>Cooper</td>
        <td>Vikings</td>
        <td>Giants</td>
        <td>Rams</td>
    </tr>
    <tr>
        <td>Jon Doe</td>
        <td>Bears</td>
        <td></td> 
        <td>Seahawks</td>
    </tr>
</tbody>

我的数据将是这样的:

{
 "name" : "Cooper",
 "picks" [{"w1": "vikings"}, {"w2" : "Giants"}, {"w3" : "Rams"}]
},
{
 "name" : "Jon Doe",
 "picks" [{"w1": "Bears"}, {"w3" : "Seahawks"}]
}

我正在寻找有关如何最好地创建输出的建议。这只是一个简单的例子,我的真实模型将有30列,所以我可能会隐藏其中的一些,具体取决于它是什么周。选秀权将按顺序进行,但我不能确定所有周都会有代表。在上面的例子中,Jon Doe忘了在第2周做出选秀。

由于

1 个答案:

答案 0 :(得分:1)

此解决方案要求您的数据结构从数组切换到包含每周键的对象。它不需要你将虚拟记录或未定义的记录插入到数组中,尽管我认为解决方案不一定那么糟糕。

下面的代码段显示了可以解决您问题的指令。请注意,在指令的html(tbody元素)中,我将max-columns设置为3以匹配您的数据。

angular.module("app", [])
  .controller("pickersCtrl", ['$scope',
    function($scope) {
      $scope.data = [{
        "name": "Cooper",
        "picks": {
          "w1": "Vikings",
          "w2": "Giants",
          "w3": "Rams"
        }
      }, {
        "name": "Jon Doe",
        "picks": {
          "w1": "Bears",
          "w3": "Seahawks"
        }
      }];
    }
  ])
  .directive("pickersRepeat", [
    function() {
      return {
        restrict: 'EA',
        scope: {
          pickers: '=',
          maxColumns: '@'
        },
        link: function(scope, element, attrs) {
          scope.$watch("pickers", function(pickers) {
            if (!pickers) {
              return;
            }
            var maxColumns = +scope.maxColumns;
            for (var i = 0; i < pickers.length; i++) {
              var picker = pickers[i];
              var row = angular.element('<tr/>');
              element.append(row);
              var nameColumn = angular.element('<td/>').text(picker.name); // append user name to Entry row
              row.append(nameColumn);
              var picks = picker.picks; // get user picks
              
              for (var j = 0; j < maxColumns; j++) {
                var column = angular.element('<td/>');
                row.append(column);
                var pick = picks["w" + (j + 1)]; // since the wX seem to start with 1 instead of 0 we add 1 here
                if (pick) {
                  // user made a pick for week j
                  column.text(pick); // put the text in column j
                }
              }
            }
          });
        }
      };
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <table ng-controller="pickersCtrl">
    <thead>
      <tr>
        <th>Entry</th>
        <th>1</th>
        <th>2</th>
        <th>3</th>
      </tr>
    </thead>
    <tbody pickers-repeat pickers="data" , max-columns="3">
    </tbody>
  </table>
</div>