Angular:从json map

时间:2016-03-05 20:51:27

标签: angularjs json

我尝试创建一个像Full Tilt Payout Structure这样的表格。我决定创建下一张地图:

$scope.payoutStructure = {
    '2-4': {
        1: 100,
        2: 0,
        3: 0,
        4: 0,
        5: 0,
        6: 0,
    },
    '6-7': {
        1: 65,
        2: 35,
        3: 0,
        4: 0,
        5: 0,
        6: 0,
    }
}

等......

但我无法弄清楚如何渲染它。如果我没有弄错的话,起初我必须像这样渲染标题:

<thead>
    <tr>
    <th><strong>Position \ Entries</strong></th>
    <th ng-repeat="key in payoutStructure.keys()">{{key}}</th> //I'm not sure about .keys(), because they are not render in order as I know                            
    </tr>
</thead>

但我无法了解如何渲染 tbody 。看起来我必须使用数组而不是地图,但我希望通过以下键获得价值:

{{payoutStructure[entries]['1']}}

2 个答案:

答案 0 :(得分:1)

1)标题你应该像

一样呈现
    $scope.payoutStructure = ['2-4','6-7','8-9', '10-18', '18-45'];
    $scope.payoutData = [
        [100, 65, 50, 40, 38],
        [0, 35,30,30,25]
    ]

   <table class="table">
        <tr>
        <th ng-repeat="header in payoutStructure">{{header}}</th>
        </tr>
    <tr ng-repeat="row in payoutData">
        <td ng-repeat="value in row track by $index" >{{value}} </td>
    </tr>
    </table>

2) 至于tbody - 它由行(而不是列)呈现,所以你的结构 应该遵循这个结构。

它可以像这样:

USERID ------ SCORE
1999 --------  100
1999 --------  230
2000 --------  210

答案 1 :(得分:1)

以下内容适用于您的数据结构:

<table class="table">
  <thead><tr>
      <th>Finishing Position</th>
      <th ng-repeat="(key, value) in payoutStructure">{{key}}</th>
  </tr></thead>
  <tbody>
    <tr ng-repeat="key in payoutStructure['2-4']">
      <th scope="row">{{$index +1}}</th>
      <td>{{payoutStructure['2-4'][$index+1]}}</td>
      <td>{{payoutStructure['6-7'][$index+1]}}</td>
    </tr>
  </tbody>
</table>

<小时/> 但如果您更改数据结构,则更好一点:

(function(angular) {
  'use strict';
  angular.module('ngRepeat', [])
    .controller('repeatController', function($scope) {
      $scope.payouts = {
        '2-4': [100],
        '6-7': [65, 35],
        '8-5': [50, 30, 20],
        '10-18': [40, 30, 20, 10],
        '18-45': [38, 25, 16, 10, 6, 5]
      };

      $scope.maxArray = [];

      angular.forEach($scope.payouts, function(value, key) {
        if (value.length > $scope.maxArray.length)
          $scope.maxArray = value;
      });

    });
})(window.angular);

这里是$scope.maxArray我们用最大数据数组长度编写支付。现在您可以使用ng-repeat输出它:

<table class="table">
  <thead><tr>
      <th>Finishing Position</th>
      <th ng-repeat="(key, value) in payouts">
        {{key}}
      </th>
  </tr></thead>
  <tbody>
    <tr ng-repeat="key in maxArray track by $index">
      <th scope="row">{{$index + 1}}</th>
      <td ng-repeat="payout in payouts">
        {{payout[$parent.$index]}}
      </td>
    </tr>
  </tbody>
</table>

关于plunker的结果: http://plnkr.co/edit/n5BfCtqjUKJ7LxvtxIFp?p=preview

<小时/> 和ngRepeat指令的官方API文档: https://docs.angularjs.org/api/ng/directive/ngRepeat