I have an array of objects, and I want to display 2 for each row, using ng-repeat.
The solution I came up with is the following:
<div ng-repeat="element in elements">
<div layout="row" ng-if="$even">
<div flex>
<span>{{ elements[$index].name }}</span>
</div>
<div flex>
<span>{{ elements[$index+1].name }}</span>
</div>
</div>
</div>
The problem is that with this I am not able to filter the contents with | filter
in the right way, since it would show the filtered elements and the following ones.
What's the best way to address the problem?
Sorry for my bad english, it's not my first language. Thank you in advance.
NEST TWO ng-repeatThe first ng-repeat in the tr tag will create the rows and the second one in the td tag will create one column per element in the collection. By using one ng-repeat for the row and an other for the column, the rows and the columns of your table is now driven by a subset.
Track by $index in AngularJSThe ngRepeat track by $index allows you to specify which items should be repeated using their index number. The ngRepeat is a directive that can be added to the HTML template of an Angular application. It is used for creating lists, and it can take an expression as an argument.
If you have an collection of objects, the ng-repeat directive is perfect for making a HTML table, displaying one table row for each object, and one table data for each object property.
$first and $last It's common when using ng-repeat to add specific behavior to the first or last element of the loop, e.g. special styling around the edges. Instead, ng-repeat already supplies you with two ready boolean properties. $first is true for the first element, and $last is true for the last element.
A good solution will be, as @Joshua Ohana said in the comments, to pre-process your array, and then use your solution.
A quick and dirty option (without pre-processing) based on your solution, will be to filter the array inside the span element:
<div ng-repeat="element in elements">
<div layout="row" ng-if="$even">
<div flex>
<span>{{ (elements | filter:<yourFilterHere>)[$index].name }}</span>
</div>
<div flex>
<span>{{ (elements | filter:<yourFilterHere>)[$index+1].name }}</span>
</div>
</div>
</div>
but I like the pre-processing option better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With