3

I'm iterating over a range and populating new select options for each index. The options are not related to the range I am iterating over but are options of different types. Code as follows:

<div ng-repeat="i in range(booking.numberOfRooms) track by $index">
    <p>Room {{$index + 1}}</p>
    <select ng-model="booking.roomSelection[$index]" ng-options="obj.roomType as obj.roomType for obj in roomTypes" ng-init="booking.roomSelection[$index] = { id: $index + 1, roomType: 'Double' }"> </select>
</div>

How can I assign an object array to ng-model (Like that in ng-init)? E.g. For two rooms, the result of ng-model should look something like:

booking.roomSelection = [{id: 1, roomSelection: 'Double'}, {id: 2, roomSelection: 'Double'}]
jcubic
  • 61,973
  • 54
  • 229
  • 402
Imran NZ
  • 1,327
  • 2
  • 12
  • 22

2 Answers2

1

Simply bind to your booking.roomSelection and remove the ng-init.If you will select two options, their value will be pushed into the booking.roomSelection and booking.roomSelection will be an array

<select multiple ng-model="booking.roomSelection" ng-options="obj.roomType as obj.roomType for obj in roomTypes"></select>
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • Unfortunately, this does not push to the ng-model, it only assigns the value of the selection which gets overwritten with the value of the selected option. I.e. book.roomSelection will only ever be a single value. – Imran NZ Aug 18 '16 at 08:23
  • @ImranNZ You want to select 2 options and get their values in the `booking.roomSelection`, yes? – Suren Srapyan Aug 18 '16 at 08:24
  • Add the `multiple` attribute on the select – Suren Srapyan Aug 18 '16 at 08:26
  • Thanks for trying to help Suren, I should have made it clear. I have a new drop box for each room (Not a multiple select). – Imran NZ Aug 18 '16 at 08:30
1

Turns out that the ng-model attribute had to be changed to: booking.roomSelection[$index].roomType

The object array must also be declared in the controller, e.g. $scope.booking.roomSelection = [];

The full declaration being:

<div ng-repeat="i in range(booking.numberOfRooms) track by $index">
    <p>Room {{$index + 1}}</p>
    <select ng-model="booking.roomSelection[$index].roomType" ng-options="obj.roomType as obj.roomType for obj in roomTypes" ng-init="booking.roomSelection[$index] = { id: $index + 1, roomType: 'Double' }"></select>
</div>
Imran NZ
  • 1,327
  • 2
  • 12
  • 22