问题
For the following code (see fiddle):
HTML:
<div ng-app ng-controller="MyCtrl">
<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>
AM/PM: {{ampm}}
</div>
JS:
function MyCtrl($scope) {
$scope.ampm = "AM";
}
The result is, HTML:
<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']" class="ng-pristine ng-valid">
<option value="0" selected="selected">AM</option>
<option value="1">PM</option>
</select>
... which is perfectly fine. However, 'AM'
and 'PM'
are being put into the ampm
model. Is it possible to put an index like 0 or 1 into this model? I want to have integer indexes which refer to the position in array, but not the value at this position which would need to recalculate.
UPDATE
Is there a way to avoid creating an array of pairs?
回答1:
You can set the select to use the index of the element as the model.
This uses the ng-options
syntax of select as label for value in array
as detailed in the Angular docs: http://docs.angularjs.org/api/ng.directive:select
I've updated the jsFiddle:
http://jsfiddle.net/EyBVN/28/
HTML:
<div ng-app ng-controller="MyCtrl">
<select
ng-model="ampm"
ng-options="options.indexOf(currOption) as currOption for currOption in options"></select>
AM/PM: {{ampm}}
</div>
JS:
function MyCtrl($scope) {
$scope.options = ['AM', 'PM'];
$scope.ampm = 0;
}
回答2:
Something like that?
<div ng-app ng-controller="MyCtrl">
<select ng-model="selectItem" ng-options="currOption as currOption.value for currOption in ampm"></select>
AM/PM: {{selectItem.name}}
</div>
controller
function MyCtrl($scope) {
$scope.ampm = [{name: "AM",value: "0" },{name: "PM",value: "1" }];
$scope.selectItem = $scope.ampm[0];
}
Demo Fiddle
来源:https://stackoverflow.com/questions/19271665/put-an-index-to-a-model-with-ng-options-for-a-simple-array