Search code examples
javascriptangularjshtml-tableangularjs-ng-repeat

Applying rowspan in table with ng-repeat angularjs


I have array like this

$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}
];

now i want to show in html like below
expected output
I tried but i can't.I attached my tried code below.

<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>

i tried but i can't find correct answer


Solution

  • The first thing you should do is transform your data into a format that's easier to iterate over. For example, you could use array.reduce() to help you create a new object that's keyed by group number. Then you can iterate over this object to create your table.

    See example snippet with comments below:

    // 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>