交替显示 2 次 ng-repeats 的结果

To display results of 2 ng-repeats alternately

我需要从 {{compNames}} 和 {{compDesc}} 返回的值交替打印,就像自上而下的堆栈一样。但是对于 2 ng-repeats,我无法以那种格式获得它。

<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>

如果我打印出 {{$ctrl.data}},我得到以下结果-

{
"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"]
}

我检查了一个类似的线程并尝试做类似下面的事情,但我认为这是错误的方法并且对我不起作用(因此我也给出了 $ctrl.data 输出)-

<div ng-repeat="data in $ctrl.data">
    <div>{{data.compNames}}</div>
    <div>{{data.compDesc}}</div>
</div>

如果你的 compNames 的长度等于 compDesc,你可以在你的 ng-repeat 中使用 length 来多次迭代 length

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

一个解决方案是预先在控制器中对两个数组执行 zip 操作,然后迭代生成的数组。

像这样:

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

然后像这样迭代它:

<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>

或者如果您在说交替时还有其他想法,您可以这样做:

<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>

请注意,您需要向 map 函数添加额外的逻辑,以防您希望两个数组的长度不同。但根据您的数据,这似乎不是问题。