在 select 中为 ng-model 分配一个对象
Assign ng-model an object in a select
我正在迭代一个范围并为每个索引填充新的 select 选项。这些选项与我正在迭代的范围无关,而是不同类型的选项。代码如下:
<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-model(就像在 ng-init 中那样)?例如。对于两个房间,ng-model 的结果应该类似于:
booking.roomSelection = [{id: 1, roomSelection: 'Double'}, {id: 2, roomSelection: 'Double'}]
只需绑定到您的 booking.roomSelection
并删除 ng-init
。如果您将 select 两个选项,它们的值将 pushed
变为 booking.roomSelection
booking.roomSelection
将是一个数组
<select multiple ng-model="booking.roomSelection" ng-options="obj.roomType as obj.roomType for obj in roomTypes"></select>
原来 ng-model 属性必须更改为: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>
我正在迭代一个范围并为每个索引填充新的 select 选项。这些选项与我正在迭代的范围无关,而是不同类型的选项。代码如下:
<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-model(就像在 ng-init 中那样)?例如。对于两个房间,ng-model 的结果应该类似于:
booking.roomSelection = [{id: 1, roomSelection: 'Double'}, {id: 2, roomSelection: 'Double'}]
只需绑定到您的 booking.roomSelection
并删除 ng-init
。如果您将 select 两个选项,它们的值将 pushed
变为 booking.roomSelection
booking.roomSelection
将是一个数组
<select multiple ng-model="booking.roomSelection" ng-options="obj.roomType as obj.roomType for obj in roomTypes"></select>
原来 ng-model 属性必须更改为: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>