0

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?

1
  • 1
    This is more of a JavaScript problem Brett. You just need to separate those PremiseData's by ;|| and create an object for each one based on that. Commented May 22, 2015 at 14:38

1 Answer 1

1

This is more JavaScript related than Angular, but you just need to separate those PremiseData's and build your own object.

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);        
    }
}

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>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.