0

AngularJS ng-Repeat array to rows and columns

How I might be able to use ng-repeat to create a grid like box of options. I would like to take an array repeat nth number of items and then move to the next row or column until all items.

<div class="row">
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
</div>
<div class="row">
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
    <div class="col-sm4"> ... </div>
</div>

The most reliable and technically correct approach is to transform the data in the controller.

Let’s go for a complete explanation :

  • By default AngularJS http get query returns an object
  • So if you want to use angular.fromJson() function you have first to transform object into an array.
  • And then to use the matrix function IN YOUR CONTROLLER.

Here’s a simple matrix function and usage.

$rootScope.matrixList = function(data, n) {
        var grid = [], i = 0, x = data.length, col, row = -1;
        for (var i = 0; i < x; i++) {
            col = i % n;
            if (col === 0) {
                grid[++row] = [];
            }
            grid[row][col] = data[i];
        }
        return grid;
};
  • @ Params: (list, n)
    • Where list is any array and n is an arbitrary number of columns desired per row
  • @ Return: A matrix
  • @ Note: This function is designed to orient a matrix based upon an arbitrary number of columns with variance in its number of rows. In other words, x = desired-columns, y = n.

Controller:

EventService.Inspired().then(function (data) {
    $scope.InspireList = $rootScope.matrixList(data.result, 2);
});

Then your view would look like this:

<div class="row" ng-repeat="items in InspireList"> 
    <div class="col" ng-repeat="item in items"> 
        {{item.id}}
    </div> 
</div>

Result: Ng-Repeat array to n rows and 2 columns

Ng-Repeat array to rows and columns

 

Save

Prakash S

Prakash S

I would like to introduce myself as a Software professional opting for the career in software industry. I'm Prakash S, a MCA graduate and trained as industry level practice for Software technology. Basically I am a PHP Developer but now days exploring more in HTML5, CSS, AngularJS and jQuery libraries.