问题
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>
回答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.
回答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() {
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
来源:https://stackoverflow.com/questions/48231638/to-display-results-of-2-ng-repeats-alternately