Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ng-Repeat array to rows and columns

Thanks for taking the time to read this, I was wondering 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 are listed. e.g.

assuming I had an array like [opt1,opt2,opt3,opt4,opt5,opt6,opt7] I would like to display it like this:

opt1 opt2 opt3
opt4 opt5 opt6
opt7
like image 985
user2910240 Avatar asked Oct 23 '13 07:10

user2910240


4 Answers

This is more a styling/markup problem than an AngularJS one. If you really want to, you can do:

<span ng:repeat="(index, value) in array">
    {{value}}<br ng:show="(index+1)%3==0" />
</span>

http://jsfiddle.net/JG3A5/

like image 157
Jahed Avatar answered Nov 16 '22 20:11

Jahed


Sorry for my HAML and Bootstrap3:

.row
  .col-lg-4
    %div{'ng:repeat' => "item in array.slice(0, array.length / 3)"}
      {{item}}
  .col-lg-4
    %div{'ng:repeat' => "item in array.slice(array.length / 3, array.length * 2/3)"}
      {{item}}
  .col-lg-4
    %div{'ng:repeat' => "item in array.slice(array.length * 2/3, array.length)"}
      {{item}}

There is another version, with possibility to use filters:

<div class="row">
  <div class="col-md-4" ng-repeat="remainder in [0,1,2]">
    <span ng-repeat="item in array" ng-if="$index % 3 == remainder">{{item}}</span>
  </div>
</div>
like image 21
mrded Avatar answered Nov 16 '22 20:11

mrded


If all of your items are in one single array, your best bet is to make a grid in CSS. This article should be helpful: http://css-tricks.com/dont-overthink-it-grids/

You can use $index from ng-repeat to apply the correct class for your column (in this case a 4 column grid):

<div class="col-{{ $index % 4 }}"></div>

If you have a 2 dimensional array (split into rows and columns) that opens up more possibilities like actually using an HTML table.

like image 23
ksimons Avatar answered Nov 16 '22 20:11

ksimons


I find it easier to simply use ng-repeat combined with ng-if and offsetting any indexes using $index. Mind the jade below:

div(ng-repeat="product in products")
    div.row(ng-if="$index % 2 === 0")
      div.col(ng-init="p1 = products[$index]")
          span p1.Title
      div.col(ng-if="products.length > $index + 1", ng-init="p2 = products[$index + 1]")
          span p2.Title
      div.col(ng-if="products.length <= $index + 1")
like image 23
Ricardo Pedroni Avatar answered Nov 16 '22 20:11

Ricardo Pedroni