I have a table row which I want to repeat and every row have only 4 td
<table>
<tr>
<td ng-repeat="team in Teams">{{team}}</td>
</tr>
</table>
How I can repeat Td, but on every 4 td create another tr and close previous one
I have a table row which I want to repeat and every row have only 4 td
<table>
<tr>
<td ng-repeat="team in Teams">{{team}}</td>
</tr>
</table>
How I can repeat Td, but on every 4 td create another tr and close previous one
This can be achieved by utilising the $index
special property.
If we move the ng-repeat
to the TR
element, it will produce a TR
every time.
We can then combat that behaviour by adding an ng-if
attribute that compares the current $index
against modulus 4, meaning the TR
will only be added every four iterations of the ng-repeat
.
With this done, we then can again use $index
within the four child TD
elements.
For the second and third elements, we need to increase the index by one, two and three respectively to get to the relevant positions inside the "Team"
array.
However, that poses a problem if that array isn't divisible by 4 perfectly.
So, finally, to counter that problem, we add a final set of ng-if
attributes to the secondm third and fourth TD
elements to ensure that they don't get added if there isn't infact any objects at the desired position in the array.
Resulting in the following HTML:
<table>
<tr ng-repeat="team in Teams" ng-if="$index % 4 == 0">
<td>{{Teams[$index]}}</td>
<td ng-if="$index+1 < Teams.length">{{Teams[$index + 1]}}</td>
<td ng-if="$index+2 < Teams.length">{{Teams[$index + 2]}}</td>
<td ng-if="$index+3 < Teams.length">{{Teams[$index + 3]}}</td>
</tr>
</table>
You can find more info on the special properties of ng-repeat here: Documentation: https://docs.angularjs.org/api/ng/directive/ngRepeat
https://docs.angularjs.org/api/ng/directive/ngRepeat
You could get the value from $index and put a condition on $index % 4 which would had a
</tr><tr>
!
Roughly would be like that :
repeat with team in Teams
IF $index%4 == 0
</tr><tr>
{{team}}
end-repeat
Not totally familiar with the syntax used by Angular but I guess you'll get the idea :)
Although this is an answered question, here is another alternative that makes use of filters
Just add a new filter in your app like
app.filter('GroupBy', function(){
return function(data,array, step) {
var result = [];
for(var i = 0; i<array.length;i+=step){
var _step = i+step;
result.push(array.slice(i,_step));
}
return result;
};
});
And in your template, use
<tr ng-repeat="team in Teams | GroupBy:Teams :4">
<td ng-repeat="t in team">{{t}}</td>
</tr>