3

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>
Mistalis
  • 17,793
  • 13
  • 73
  • 97
lettman1
  • 95
  • 6
  • *"linking to an ng-init"* ... this is not what `ng-init` is for (see docs). Use controller to handle business logic like this – charlietfl Jul 13 '17 at 14:10

1 Answers1

0

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" 
Mistalis
  • 17,793
  • 13
  • 73
  • 97
  • This worked! Thanks so much I will accept answer once it lets me. – lettman1 Jul 13 '17 at 14:15
  • This makes the fallback work. Which is great but now I am realizing that the first part just never worked at all. I think @charlietfl comment is correct. – lettman1 Jul 13 '17 at 14:27
  • @lettman1 So you can just init this variable in your controller: `$scope.autoship.baddress_id = whatever;` – Mistalis Jul 13 '17 at 14:43