Reputation: 1973
I'm new to Angular and this is my first major hurdle. I have the following JSON object returned from a third-party API of address data that's been added to $scope.AddressData in a controller:
$scope.AddressData = [{
"Address1":"South Row",
"Address2":"Horsforth",
"Address3":null,
"Address4":null,
"Town":"Leeds",
"County":"West Yorkshire",
"Postcode":"LS18 4AA",
"PremiseData":"12;||13;||14;"
}];
As you can see, I have multiple premises for one street. What I want to achieve is to have a select box that has one line per PremiseData item with the other fields appended to it.
Given the example above, I want the HTML to be:
<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>
Also, once an item is selected, I want to populate other inputs with the relevant data.
Can anyone point me in the right direction?
Upvotes: 0
Views: 1552
Reputation: 67181
This is more JavaScript related than Angular, but you just need to separate those PremiseData
's and build your own object.
// 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);
}
}
Then in your html you simply use ng-options
to loop through those addresses
, and voila!
<select ng-model="selectedAddress" ng-options="a as a for a in addresses"></select>
Upvotes: 1