我是Angular的新手,这是我的第一个主要障碍。我从地址数据的第三方API返回以下JSON对象,该API已添加到控制器中的$ scope.AddressData:
$scope.AddressData = [{
"Address1":"South Row",
"Address2":"Horsforth",
"Address3":null,
"Address4":null,
"Town":"Leeds",
"County":"West Yorkshire",
"Postcode":"LS18 4AA",
"PremiseData":"12;||13;||14;"
}];
如您所见,我有一条街道的多个处所。我想要实现的是有一个选择框,每个PremiseData项目有一行,并附加其他字段。
鉴于上面的示例,我希望HTML为:
<select name="premises">
<option value="12 South Row, Horsforth, Leeds, West Yorkshire"></option>
<option value="13 South Row, Horsforth, Leeds, West Yorkshire"></option>
<option value="14 South Row, Horsforth, Leeds, West Yorkshire"></option>
</select>
此外,一旦选择了一个项目,我想用相关数据填充其他输入。
有人能指出我正确的方向吗?
答案 0 :(得分:1)
这与Angular相关的JavaScript更多,但您只需将这些PremiseData
分开并构建自己的对象。
<强> jsFiddle Demo 强>
// No point in adding this to your scope since you're not using it there
var addressData = [{
"Address1":"South Row",
"Address2":"Horsforth",
"Address3":null,
"Address4":null,
"Town":"Leeds",
"County":"West Yorkshire",
"Postcode":"LS18 4AA",
"PremiseData":"12;||13;||14;"
}];
$scope.addresses = [];
for (var i = 0; i < addressData.length; i++) {
// Remove that last " ; "
addressData[i].PremiseData = addressData[i].PremiseData.substr(0, addressData[i].PremiseData.length - 1);
// Split by ;||
var premises = addressData[i].PremiseData.split(';||');
// Build new address
for (var n = 0; n < premises.length; n++) {
var address = premises[n] + ' '
+ addressData[i].Address1 + ' '
+ addressData[i].Address2 + ' '
+ addressData[i].Town + ' '
+ addressData[i].County;
// Add this built address to your
$scope.addresses.push(address);
}
}
然后在您的HTML中,您只需使用ng-options
循环浏览addresses
,瞧!
<select ng-model="selectedAddress" ng-options="a as a for a in addresses"></select>