2

I want to display my data in table rows, with 2 element per row.

For example, if I have this array:

['dinesh', 'kumar', 'mahesh', 'rathore']

The result should look like:

--------------------
| dinesh | kumar   |
--------------------
| mahesj | rathore |
--------------------

When I put the ng-repeat in the tr, each row has one cell.

When I put the ng-repeat in the td, I am getting a single row with 4 cells

I tried using $index + 1 but it did not change the actual index value. So I am getting repeated elements. What's the solution?

Dave Cassel
  • 8,352
  • 20
  • 38
dinesh kumar
  • 103
  • 8

2 Answers2

1

$index is the current repeat iteration. You cannot change the index value, you can only use it for display purpose.


There is a similar post on stackoverflow

A solution would be to repeat over a splitted model:

function chunk(arr, size) {
  var newArr = [];
  for (var i=0; i<arr.length; i+=size) {
    newArr.push(arr.slice(i, i+size));
  }
  return newArr;
}

$scope.chunkedData = chunk(['dinesh', 'kumar', 'mahesh', 'rathore'], 3);

Then:

<table>
  <tr ng-repeat="row in chunkedData">
    <td ng-repeat="element in row">
      {{element}}
    </td>
  </tr>
</table>

(Follow the link if you need to order items verticaly)


But using table tr/td is a full pain. Using div with css is probably a better solution. It would look like

<div ng-repeat="element in elements" ng-style="{'float:left;' : $even}">
      {{element}}
</div 
Community
  • 1
  • 1
jbigman
  • 1,200
  • 11
  • 24
1

add this to your javascript code..

    // divide array
Array.prototype.divideIt = function(d){
    if(this.length <= d) return this;
    var arr = this,
        hold = [],
        ref = -1;
    for(var i = 0; i < arr.length; i++){
        if(i % d === 0){
            ref++;
        }
        if(typeof hold[ref] === 'undefined'){
            hold[ref] = [];
        }
        hold[ref].push(arr[i]);
    }

    return hold;
};

Then use the following angularjs solution (similar to jbigman solution):

<div ng-app>
    <table>
        <tr ng-repeat="subModel in ['dinesh', 'kumar', 'mahesh', 'rathore'].divideIt(2)">
            <td ng-repeat="element in subModel ">{{element}}</td>
        </tr>
    </table>
</div>

// divide array
Array.prototype.divideIt = function(d) {
  if (this.length <= d) return this;
  var arr = this,
    hold = [],
    ref = -1;
  for (var i = 0; i < arr.length; i++) {
    if (i % d === 0) {
      ref++;
    }
    if (typeof hold[ref] === 'undefined') {
      hold[ref] = [];
    }
    hold[ref].push(arr[i]);
  }

  return hold;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <table>
    <tr ng-repeat="subModel in ['dinesh', 'kumar', 'mahesh', 'rathore'].divideIt(2)">
      <td ng-repeat="element in subModel ">{{element}}</td>
    </tr>
  </table>
</div>
Dror Hilman
  • 6,837
  • 9
  • 39
  • 56