Home To display results of 2 ng-repeats alternately
Reply: 2

To display results of 2 ng-repeats alternately

manishk
1#
manishk Published in 2018-01-12 17:53:45Z

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.

<div class="title">
    <table>
        <tr>
            <td class="comp-names" ng-repeat="compNames in $ctrl.data.compNames track by $index">{{compNames}}</td>
        </tr>
        <tr>
            <td class="comp-desc" ng-repeat="compDesc in $ctrl.data.compDesc track by $index">{{compDesc}}</td>
        </tr>
    </table>
</div>

If I print out {{$ctrl.data}}, I get the following-

{
"details": {
    "comp": { 
        "id": "12345",
        "company_name": "Google",
        "date_created": "2018-01-10 18:03:27",
        "file_name":"Admin.txt"
    }
},
"compNames": ["five","nine","twelve"],
"compDesc": [" String combinations"," String combinations"," String manipulation to eval"]
}

I checked a similar thread and tried to do something like the following but I think it's the wrong approach and doesn't work for me (hence I have given the $ctrl.data output as well)-

<div ng-repeat="data in $ctrl.data">
    <div>{{data.compNames}}</div>
    <div>{{data.compDesc}}</div>
</div>
Nikolaj Dam Larsen
2#
Nikolaj Dam Larsen Reply to 2018-01-12 18:58:58Z

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.

NTP
3#
NTP Reply to 2018-01-12 21:33:21Z

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() {
    return new Array( $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

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.331443 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO