You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在repeat循环中通过$index绑定数组对象的value.bind

如何在Aurelia动态表单中根据索引和属性名绑定数组对象值

我用repeat构建了一个动态表单,想把表单输入值绑定到数组对象里,通过$index把值设置到数组对应的对象中。请问怎么根据当前索引和属性名称设置数组中的绑定?

代码示例

JavaScript代码

// 动态表单配置项
guaranteeItems = [
    {
        type: 'text',
        label: 'firstName',
        property: 'personFirstName'
    },
    {
        type: 'text',
        label: 'lastName',
        property: 'personLastName'
    },
]

// 要绑定的数据源数组
guarantee = [
    {
        personFirstName: '',
        personLastName: '',
        personProfession: '', // 修正原拼写错误
        personMainIdentityTypeId: '',
        personMainIdentityNo: '',

        addressStreetName: '',
        addressStreetNo: '',
        addressEntrance: '',
        addressCityId: '',
        no: ''
    }]  

HTML代码(原错误写法)

<template repeat.for="testInput of guaranteeItems">
    <label>${$index + 1}.*</label>
    <div>
        <label for="fname">${testInput.label}</label> <!-- 正常工作 -->
        <input type="text" value.bind="guarantee[${$index}].$index.property" required> <!-- 绑定失败 -->
    </div> 
</template>

解决方案

你当前的绑定表达式存在两个问题:一是Aurelia绑定语法不支持模板字符串${}写法,二是$index.property的写法完全错误,没法正确指向配置项里的属性名。

单组数据绑定(guarantee数组只有一个对象)

直接用括号属性访问语法,通过配置项的property字段动态指定要绑定的属性:

<template repeat.for="testInput of guaranteeItems">
    <label>${$index + 1}.*</label>
    <div>
        <label for="${testInput.property}">${testInput.label}</label>
        <input type="text" id="${testInput.property}" value.bind="guarantee[0][testInput.property]" required>
    </div> 
</template>
  • guarantee[0]:取数据源数组里的第一个对象(因为你的guarantee目前只有一组数据)
  • [testInput.property]:动态访问对象的属性,比如当testInput是第一项时,就对应personFirstName

多组数据绑定(guarantee数组有多份对象)

如果需要渲染多份担保信息,在外层再加一层repeat循环数据源数组,直接绑定当前循环的对象:

<!-- 外层循环多组担保数据 -->
<template repeat.for="currentGuarantee of guarantee">
    <h3>第${$index + 1}份担保信息</h3>
    <!-- 内层循环表单配置项 -->
    <template repeat.for="testInput of guaranteeItems">
        <label>${$index + 1}.*</label>
        <div>
            <label for="${testInput.property}-${$parent.$index}">${testInput.label}</label>
            <input 
                type="text" 
                id="${testInput.property}-${$parent.$index}" 
                value.bind="currentGuarantee[testInput.property]" 
                required
            >
        </div> 
    </template>
</template>

这里用currentGuarantee[testInput.property]直接绑定,既简洁又不会出错,还能自动对应每组数据的属性。

另外注意修正原代码里的小问题:

  • 配置项里的label值引号没闭合,已经在示例中修正
  • personProffesion拼写错误,改成了personProfession(不影响功能,但建议修正)

内容的提问来源于stack exchange,提问作者user384496

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:07:04