有棱角的将数据字典中的数据绑定到对象

Angular. Binding data from data dictionaries to objects

本文关键字:数据绑定 对象 数据字典      更新时间:2024-04-28

在angular中,我有几个集合。第一个是全球"产品属性"词典:

attributes : [
    {id:1, value:"red", type:"color"}, 
    {id:2, value:"green", type:"color"}, 
    {id:3, value:"big", type:"size"}
]

我有一个"产品"对象:

cars : [{
    name : "red big car",
    attributes : [1, 3] # id's corresponding to 'attributes' list
}]

现在在我的模板中,我想以一种简单的方式访问这些数据:

<div ng-repeat='car in cars'>
    <p>{{ car.name }}</p>
    <p ng-repeat='attribute in attributes'>{{ attribute.value }}</p>
</div>

要获得结果:

<div ng-repeat='car in cars'>
    <p>red big car</p>
    <p ng-repeat='attribute in attributes'>red</p>
    <p ng-repeat='attribute in attributes'>big</p>
</div>

我知道我可以迭代它,并将所有的"属性"数据复制到"汽车",但这会对我的数据产生大量无用的副本。还有其他想法吗
提前感谢:)

如果没有一种干净的数学方法来计算基于ids的数组索引(就像您当前的示例中索引为(id-1)),那么我会创建一个查找表,以数据库通常的方式将数组索引值映射到ids

$scope.lookup = {1:0,
                 2:1,
                 3:2 }

然后使用它将car属性数组索引映射为属性数组中的数组索引:

<div ng-repeat='car in cars'>
    <p>{{ car.name }}</p>
   {{car.attributes}}
   <p ng-repeat='indx in car.attributes'>{{attributes[lookup[indx]].value }}</p>
</div>

小提琴