3

我遍历一个范围并为每个索引填充新的选择选项。选项与我正在迭代的范围无关,但是是不同类型的选项。代码如下:在选择中指定对象

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

我如何分配一个对象数组到NG-模型(像在NG-INIT)?例如。对于两房,NG-模型的结果应该是这个样子:

booking.roomSelection = [{id: 1, roomSelection: 'Double'}, {id: 2, roomSelection: 'Double'}] 

回答

1

原来,NG-模型属性必须被更改为:booking.roomSelection[$index].roomType

对象阵列也必须是在控制器中声明,例如$scope.booking.roomSelection = [];

完整的声明之中:

<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> 
+0

你也可以使用'ng-model =“booking.roomSelection [$ index]”'if'ng-options =“obj as obj.roomType for obj in roomTypes”'。 –

1

只需绑定到booking.roomSelection并删除ng-init。如果你将选择两个选项,其价值将是pushedbooking.roomSelectionbooking.roomSelection会是一个数组

<select multiple ng-model="booking.roomSelection" ng-options="obj.roomType as obj.roomType for obj in roomTypes"></select> 
+0

不幸的是,这并不能推到NG-模型,它只赋予其获取与所选择的选项的值覆盖所选内容的价值。即book.roomSelection将永远只是一个单一的价值。 –

+0

@ImranNZ你想选择2个选项并在'booking.roomSelection'中获取它们的值,是的? –

+0

在选择 –