AngularJS,根据另一个数组当前位置显示数组值

问题描述 投票:0回答:1

在javascript中,有两个数组,它们的长度相等,但长度是未知的,基于一些db值。例如

colName=['col1','col2','col3'];
fieldValue=['abc','def','ghi'];

colName=['col1','col2','col3', 'col4'];
fieldValue=['abc','def','ghi', 'lmn'];

或者 colName.length = x, fieldValue.length = x

其中 x 是变量。

然后在html中,使用angularjs我想根据当前检索fieldValue位置的位置显示colName值。

例如

<tr ng-repeat="fieldValue in form.fieldValue track by $index">
    <td> {{colName[{{$index}}]}}</td>
    <td> {{fieldValue}} </td> 
</tr>

当然这部分是失败的

<td> {{colName[{{$index}}]}}</td>

那么如何根据当前fieldValue位置显示colName[x]呢?

预期结果:(colX 数量是动态的)

col1 abc
col2 定义
col3 ghi

angularjs
1个回答
0
投票

在 AngularJS 中,根据当前元素在 fieldValue 数组中的位置显示 colName 数组对应的值,不需要使用 {{$index}} 直接对 colName 数组进行索引。相反,您可以利用 ng Repeat 的功能,它已经在内部跟踪当前迭代的索引。 正确的做法是直接在ng Repeat指令中使用colName数组对应的索引,而不需要{{$index}}。在 ng Repeat 中,每次迭代 fieldValue 数组时,AngularJS 都会自动将当前元素与 colName 数组的相应元素配对。 以下是正确 HTML 代码的示例:

<tr ng-repeat="(index, fieldValue) in form.fieldValue track by $index">
    <td> {{colName[index]}}</td>
    <td> {{fieldValue}} </td> 
</tr>

在这个例子中,(index, fieldValue)是ng重复迭代形式的解构。字段值。 Index 是当前元素在 fieldValue 数组中的索引,fieldValue 是当前元素本身。通过 $index 进行跟踪可确保即使两个数组中的元素顺序发生变化,迭代也保持同步。 这样,eachtag就会显示colName数组中当前fieldValue元素对应的值。 因此,如果 colName 数组和 fieldValue 数组具有相同的长度和顺序,则上述代码将按预期工作。如果数组长度不同或者顺序不一致,则无法保证结果,所以在实际应用中保证这两个数组是同步的。

© www.soinside.com 2019 - 2024. All rights reserved.