Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS how to dynamically split list in multiple columns

Tags:

angularjs

I have a number of li items which I want evenly distributed across 3 different columns. So I need the 1st third of the list items to be shown in the first ul, the next third in the 2nd ul etc.

Right know my approach is somewhat static:

<ul class="small-12 medium-4 columns">
  <li ng-repeat="skill in skills.development | slice:0:10">
    {{ skill.name }}
  </li>
</ul>
<ul class="small-12 medium-4 columns">
  <li ng-repeat="skill in skills.development | slice:10:21">
    {{ skill.name }}
  </li>
</ul>
<ul class="small-12 medium-4 columns">
  <li ng-repeat="skill in skills.development | slice:21:32">
    {{ skill.name }}
  </li>
</ul>

I create the 3 rows in my template and then I created a custom filter that slices the list so I can obtain the first 11 elements, the next 11 elements and so forth. Problem is that the number of rows in each ul is not assigned dynamically like so:

Math.ceil(skills.development.length / 3)

So if I have more elements I will have to manually change the number of rows. Filtering is an issue as well. Imagine that I search for a word with 5 matches in first column and one in the 2nd column. Then I would have completely uneven column sizes. The length should be recalculated dynamically when I filter the list.

Ideally not only the number of rows in a column is calculated dynamically, but also the number of columns. So if there are more than say 15 elements it should render three columns, but if there is only 10 elements 2 columns will look better (as there is only 5 elements in each). And if there are less than 5 elements only one column will be rendered.

I figured that I should either try to solve it in the view or make some sort of helper function similar to the custom filter function I already wrote. But how might I do that?

like image 588
zkwsk Avatar asked Sep 03 '14 23:09

zkwsk


1 Answers

Create a columns array with start and end values for each column and use a nested repeater to loop through all the data and render properly.

<ul ng-repeat="column in columns" class="small-12 medium-4 columns">
  <li ng-repeat="skill in skills | slice:column.start:column.end">
    {{ skill }}
  </li>
</ul>

Full plnkr here: http://plnkr.co/edit/AMWLvB045UJmNamp8vdz?p=preview

like image 154
Samuel Neff Avatar answered Sep 28 '22 01:09

Samuel Neff