Imran NZ
Imran NZ

Reputation: 1347

Assign ng-model an object in a select

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'}]

Upvotes: 3

Views: 439

Answers (2)

Imran NZ
Imran NZ

Reputation: 1347

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>

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68635

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>

Upvotes: 1

Related Questions