Search code examples
javascriptangularjsng-optionsng-init

ng-options with array of objects linking to an ng-init


I am creating a select with ng-options that loops through an array of objects linking to an ng-init. However, the problem is, it has to pass the correct variable through ng-change as well.

Right now the code below will make ng-init work and pick the right option on load. However, when the options are selected it doesn't pass the id to the ng-change

<select name="baddress" ng-init="autoship.baddress_id = address.id || addresses[0]" 
ng-model="autoship.baddress_id" 
ng-change="setter('baddress', autoship, address.id)" 
ng-options="address as address.address + ' ' + address.address2 + ' ' + address.city + ', ' + address.state + ' ' + address.zipcode for address in addresses" ></select>

By adding .id to address in the beginning of the ng-options, the ng-change works perfectly but it leaves the select drop down empty on load.

<select name="baddress" 
ng-init="autoship.baddress_id = address.id || addresses[0]" 
ng-model="autoship.baddress_id" 
ng-change="setter('baddress', autoship, address.id)" 
ng-options="address.id as address.address + ' ' + address.address2 + ' ' + address.city + ', ' + address.state + ' ' + address.zipcode for address in addresses" ></select>

Solution

  • adresses[0] will be the whole address object in this line:

    ng-init="autoship.baddress_id = address.id || addresses[0]" 
    

    In order to only keep the id, I think you should change it to:

    ng-init="autoship.baddress_id = address.id || addresses[0].id"