Skip to content Skip to sidebar Skip to footer

To Display Results Of 2 Ng-repeats Alternately

I need the values returned from {{compNames}} and {{compDesc}} to print alternately, like a top-down stack. But with the 2 ng-repeats I'm not able to get it in that format.

Solution 1:

One solution is to do a zip-operation on the two arrays beforehand in your controller and then iterate over the resulting array.

Something like this:

ctrl.combined = ctrl.data.compNames.map(function(value, index){
    return { name: value, desc: ctrl.data.compDesc[index] };
});

and then iterate over it like this:

<tr ng-repeat="comp in $ctrl.combined track by $index">
    <td class="comp-names">{{comp.name}}</td>
    <td class="comp-desc">{{comp.desc}}</td>
</tr>

or in case you had something else in mind when you said alternating, you can do something like this:

<tr ng-repeat-start="comp in $ctrl.combined track by $index">
    <td class="comp-names">{{comp.name}}</td>
</tr>
<tr ng-repeat-end>
    <td class="comp-desc">{{comp.desc}}</td>
</tr>

Beware that you need to add extra logic to the map-function, in case you expect the two arrays to be of different lengths. But based on your data, it doesn't seem like that'll be an issue.

Solution 2:

if length of your compNames is equal to compDesc, you can use length in your ng-repeat to iterate length many times

js

$scope.getNumber = function() {
    returnnewArray( $scope.data.compNames.length);
}

html

<div ng-repeat="i in getNumber() track by $index">
    <div>{{data.compNames[$index]}}</div>
    <div>{{data.compDesc[$index]}}</div>
</div>

demo

Post a Comment for "To Display Results Of 2 Ng-repeats Alternately"