admin管理员组

文章数量:1289384

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?

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?

Share Improve this question edited Oct 9, 2013 at 12:33 Andrey Chaschev asked Oct 9, 2013 at 12:12 Andrey ChaschevAndrey Chaschev 16.5k5 gold badges56 silver badges69 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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/api/ng.directive:select

I've updated the jsFiddle:

http://jsfiddle/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;
}

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

本文标签: javascriptPut an index to a model with ngoptions for a simple arrayStack Overflow