交替显示2个ng-repeats的结果 [英] To display results of 2 ng-repeats alternately

查看:180
本文介绍了交替显示2个ng-repeats的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从{{compNames}}和{{compDesc}}返回的值像自上而下的堆栈一样交替打印.但是使用2 ng重复,我无法以这种格式获取它.

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>

如果我打印出{{$ ctrl.data}},则会得到以下内容-

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

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

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>

推荐答案

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

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

类似这样的东西:

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>

或者当您说交替说话时,如果您有其他想法,可以执行以下操作:

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>


请注意,如果您希望两个数组的长度不同,则需要在map函数中添加额外的逻辑.但是根据您的数据,看来这不会成为问题.


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个ng-repeats的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆