0

I need to build HTML table using angular on a data which has inconsistent number of columns cell in different rows. I need to display shaded cells for columns having lesser number of columns in any particular row. For example -

Data:

a,b,c,d
1,2,3
4,5,6,7
8,9,10,11,12

Expected output: expected output

Can this behavior be achieved using ng-repeat or some other way?

2
  • Did you try anything at your own? Commented Mar 26, 2018 at 7:34
  • I tried creating another array for the cells to be appended under HTML, but didn't succeed. Commented Mar 26, 2018 at 7:38

1 Answer 1

1

You can find the largest collection of items, and then loop over it to create tds. Following is a working example, read the code comments to understand its working:

angular.module('app', [])
  .controller('ctrl', function($scope) {
    // The original data
    let data = 'a,b,c,d\n1,2,3\n4,5,6,7\n8,9,10,11,12';

    // Create arrays out of the original data. This will be used to render the table
    $scope.data = data.split('\n')
      .map(item => item.split(','));

    // Find the maximum number of elements so that we can create that much td elements
    $scope.max = Math.max(...$scope.data.map(item => item.length));

    // Helper function to create an array out of given length
    $scope.getArray = length => new Array(length);
  });
td {
  border: 1px solid black;
  width: 50px;
}

.blank {
  background-color: lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <table>
    <!--Loop over the rows of data-->
    <tr ng-repeat="row in data">
      <!--Loop over an empty array-->
      <td ng-repeat="_ in getArray(max) track by $index" ng-class="{blank: !row[$index]}">
        {{row[$index]}}
      </td>
    </tr>
  </table>
</div>

For graying out the unavailable items, it uses ng-class directive to assign a blank class to the td, which is then colored using CSS.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.