使用ng-repeat angularjs在表格中应用rowspan

问题描述 投票:1回答:1

我有这样的数组

$scope.orderno=[
{"orderno":1254,"weight":25875,"group":5},
{"orderno":56787,"weight":25875,"group":5},
{"orderno":567,"weight":25875,"group":3},
{"orderno":123254,"weight":25875,"group":3}
];

现在我想在html中显示如下 expected output 我试过但我不能。我在下面附上了我试过的代码。

<div ng-app>
  <table ng-controller="MainCtrl">
    <thead>
      <div>
        <tr>
          <td>orderno</td>
          <td>weight</td>
          <td rowspan={{orderwt}}>group</td>
        </tr>
      </div>
    </thead>
    <tbody ng-repeat="item in orderno">
      <tr>
        <td></td>       
        <td></td>
        <td rowspan="{{orderno.length}}">{{item.group}}</td>
      </tr>
      <tr>
        <td>{{item.orderno}}</td>     
        <td>{{item.weight}}</td>
      </tr>
    </tbody>
  </table>
</div>

我试过,但我找不到正确的答案

javascript angularjs html-table angularjs-ng-repeat
1个回答
1
投票

您应该做的第一件事是将数据转换为更容易迭代的格式。例如,您可以使用array.reduce()来帮助您创建一个由组编号键入的新对象。然后,您可以遍历此对象以创建表。

请参阅以下评论的示例代码段:

// This is your original data array
let arr = [{
      "orderno": 1254,
      "weight": 25875,
      "group": 5
    },
    {
      "orderno": 56787,
      "weight": 25875,
      "group": 5
    },
    {
      "orderno": 567,
      "weight": 25875,
      "group": 3
    },
    {
      "orderno": 123254,
      "weight": 25875,
      "group": 3
    }
  ],  // Use reduce and Object.create to make a new object keyed by group number
  result = arr.reduce(function(r, a) {
    r[a.group] = r[a.group] || [];
    r[a.group].push(a);
    return r;
  }, Object.create(null));

let app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
  $scope.groups = result;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <table border="1">
    <thead>
      <td>Group</td>
      <td>Order No</td>
      <td>Weight</td>
    </thead>
    <tbody ng-repeat="(key, value) in groups">  <!-- Outer loop -->
      <tr ng-repeat="group in value"> <!-- Inner loop -->
        <td ng-if="$index == 0" rowspan="{{ value.length }}">{{ group.group }}</td> 
        <!-- the above is so we only add the rowspan once -->
        <td>{{ group.orderno }}</td>
        <td>{{ group.weight }}</td>
      </tr>
    </tbody>
  </table>

</div>
© www.soinside.com 2019 - 2024. All rights reserved.