Skip to content

Instantly share code, notes, and snippets.

@arvindr21
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arvindr21/75a66c4cf6ea44cafd9c to your computer and use it in GitHub Desktop.
Save arvindr21/75a66c4cf6ea44cafd9c to your computer and use it in GitHub Desktop.
<!--
-
- The below code will convert a ng-repeat which display 3 column like
- 1 | 2 | 3
- 4 | 5 | 6
- 7 | 8 | 9
- 10
- To
-
- 1 | 5 | 8
- 2 | 6 | 9
- 3 | 7 | 10
- 4
-
- Thanks to Jayesh Choudhari [https://github.com/jc17]
-->
<!doctype html>
<html ng-app="app">
<head>
<style type="text/css">
.b-1of3 {
width: 31%;
margin: 5px;
float: left;
}
br {
clear: both;
}
.col-1{
border: 1px solid red;
}
.col-2{
border: 1px solid green;
}
.col-3{
border: 1px solid blue;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.5/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<div class="b-1of3" ng-repeat="d in data | limitTo : 9">
{{d.text}}
</div>
<br/>
<hr/>
<div class="b-1of3" ng-repeat="d in data | limitTo : 11">
{{d.text}}
</div>
<br/>
<hr/>
<h2>Re-ordered data</h2>
<div class="b-1of3" ng-class=" {'col-1' : $index%3 == 0,'col-2' : $index%3 == 1,'col-3' : $index%3 == 2 }" ng-repeat="d in processedData">
{{d.text}}
</div>
</body>
<script type="text/javascript">
var app = angular.module('app', [])
.controller('MainCtrl', ['$scope', function($scope) {
// original data
$scope.data = dataFromService;
// processed data
var r = 0;
var i, j, k, c;
var nc = 3; //number of columns required
//gc gives no. of elements in each column
var mod = dataFromService.length % nc;
var rows = parseInt(dataFromService.length / nc);
var gc = new Array(nc);
for (i = 0; i < mod; i++) gc[i] = rows + 1;
for (i = mod; i < nc; i++) gc[i] = rows;
//the new empty array
var processedData = new Array(dataFromService.length);
j = 0; //j keeps the track of elements of old array
for (i = 0; i < nc; i++) {
k = i;
//we assign elements in new array column wise..
for (c = 0; c < gc[i]; c++) {
processedData[k] = dataFromService[j];
j++;
k += nc;
}
}
for (i = 0; i < processedData.length; i++)
console.log(processedData[i].text);
$scope.processedData = processedData;
}]);
var dataFromService = [{
"text": "one"
}, {
"text": "two"
}, {
"text": "three"
}, {
"text": "four"
}, {
"text": "five"
}, {
"text": "six"
}, {
"text": "seven"
}, {
"text": "eight"
}, {
"text": "nine"
}, {
"text": "ten"
}, {
"text": "eleven"
}, {
"text": "tweleve"
}];
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment