Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can make 2 columns with table in angular

I have this code in angular template which just makes the header on left and data on right from top to bottom.

<div class="panel-body">

        <table class="table table-striped">
            <tr ng-repeat="f in fields">
                <th>{{ f }}</th>
                <td>{{ data[f] }}</td>
            </tr>

        </table>

    </div>

But instead of one field in one row i want to have 2 fields in one row and 3rd field and 4th field in second row and so on.

so that i have 2 columns layout

 <tr><th>{{ f }}</th>
 <td>{{ data[f] }}</td> 
 <th>{{ f }}</th>
 <td>{{ data[f] }}</td>
</tr>


field = ['id', 'name', 'username', 'email', 'age']

data = [{id:1, name: 'john', username: 'john', age: 20, email: 'test'}]

The result i want is

<tr><td>id:</td><td>1</td><td>name:</td><td>john</td></tr>
<tr><td>username:</td><td>john</td><td>age:</td><td>20</td></tr>

This should be done with ng-repeat rather hard coding stuff

like image 340
user3214546 Avatar asked Oct 19 '22 08:10

user3214546


1 Answers

Here's an answer. I'm not sure it's exactly what you want but I think it comes close: http://plnkr.co/edit/ADKu2WEb9TyvEXASOJyz?p=preview

Note that I'm using ng-repeat-start/ng-repeat-end to handle the multi-line thing you want to do:

<body ng-app="example" ng-controller="ExampleController">
  <table>
    <tr ng-repeat-start="row in data">
      <td>{{ label(0) }}:</td>
      <td>{{ value(row, 0) }}</td>
      <td>{{ label(1) }}:</td>
      <td>{{ value(row, 1) }}</td>
    </tr>
    <tr ng-repeat-end>
      <td>{{ label(2) }}:</td>
      <td>{{ value(row, 2) }}</td>
      <td>{{ label(3) }}:</td>
      <td>{{ value(row, 3) }}</td>
    </tr>
  </table>
</body>

The rest is just a super simple module and controller:

angular.module('example', [])
  .controller('ExampleController', function ($scope) {
    var fields = [ 'id', 'name', 'username', 'email', 'age' ];
    $scope.data = [{id:1, name: 'john', username: 'john', age: 20, email: 'test'}];

    $scope.label = function (fieldNumber) {
      return fields[fieldNumber];
    };

    $scope.value = function (row, fieldNumber) {
      return row[fields[fieldNumber]];
    }
  });
like image 125
John Munsch Avatar answered Oct 24 '22 05:10

John Munsch