Search code examples
angularjshtml-tableangularjs-ng-repeat

How to display array in table using ng-repeat


Unlike other JSON data , I have simple arrays of two.

$scope.land = [ elephant, tiger, zebra ];
$scope.water = [ fish , octopus, crab];

I want to put up the array in table using ng-repeat. I tried this but data is not showing in proper format.

<table class="table table-dark">
    <thead>
        <tr>
            <th scope="col">LAND</th>
            <th scope="col">WATER</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="l in land track by $index">
            <td>{{l}}</td>
            <td>fish</td>
        </tr>
    </tbody>
</table> 

EDIT:- err in data showing vertical in table enter image description here

new data :-

$scope.land = [ 'tiger in zoo', 'tiger in jungle', 'zebra'];
 $scope.water = [ 'fish in pond'];

Solution

  • I think you are trying to display elements of two arrays next to each other (correct me if i'm wrong).

    Here is a simple way to do that :

    angular.module('myApp', [])
    .controller('TestCtrl', function ($scope) {
        $scope.land = [ 'tiger in zoo', 'tiger in jungle', 'zebra'];
        $scope.water = [ 'fish in pond'];
        $scope.combined = [];
        var maxLength = ($scope.land.length > $scope.water.length) ? $scope.land.length : $scope.water.length;
        //length is to be determined
        for(var index = 0; index < maxLength ; index++) {
        	$scope.combined.push({
          	land: ($scope.land[index]) ?  $scope.land[index] : '',
            water: ($scope.water[index]) ? $scope.water[index] : ''
          });
        }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="TestCtrl">
      <table class="table table-dark">
        <thead>
          <tr>
            <th scope="col">LAND</th>
            <th scope="col">WATER</th>
          </tr>
        </thead>
        <tbody>
          <tr ng-repeat="item in combined">
            <td>{{item.land}}</td>
            <td>{{item.water}}</td>
          </tr>
        </tbody>
      </table> 
    </div>