How to set value.bind in array using the index inside repeat

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

我有一个带有重复的动态表单构建,id 喜欢将其值绑定到数组对象,我想使用 $index 将值设置为数组中的写入对象。

如何在当前索引和属性名称的数组中设置绑定

代码

    guaranteeItems = [
    {
        type: 'text',
        label: 'firstName,
        property: 'personFirstName'
    },
    {
        type: 'text',
        label: 'lastName,
        property: 'personLastName'
    },
]

 guarantee = [
    {
        personFirstName: '',
        personLastName: '',
        personProffesion: '',
        personMainIdentityTypeId: '',
        personMainIdentityNo: '',

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

     HTML Code: 
     <template repeat.for="testInput of guaranteeItems">
        <label>${$index + 1}.*</label>
         <div>
            <label for="fname">${testInput.label}</label> // This is working
            <input type="text" value.bind="guarantee[${$index}].$index.property" required> // This is not working 
        </div> 
    </template>
binding aurelia
1个回答
0
投票

要在当前索引和属性名称处设置数组中的绑定,您可以使用以下语法进行 Aurelia 绑定:

<input type="text" value.bind="guarantee[$index][testInput.property]">

这里,

guarantee[$index]
会访问当前索引$index处的保证数组中的对象,[testInput.property]会访问当前testInput对象中指定的属性。

所以,您更新后的代码将是:

<template repeat.for="testInput of guaranteeItems">
  <label>${$index + 1}.*</label>
  <div>
    <label for="fname">${testInput.label}</label>
    <input type="text" value.bind="guarantee[$index][testInput.property]" required>
  </div> 
</template>

在您的原始代码中,您使用 ${} 尝试根据当前索引 $index 和 testInput 对象的属性值动态计算保证对象的属性名称。但是,此语法不正确并导致绑定表达式失败,因为插值语法用于显示值,而不是在绑定表达式中使用。

希望这是有道理的。

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