Search code examples
javascriptangularjsjsonangular-ngmodelangularjs-ng-init

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

Solution

  • 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>