Put an index to a model with ng-options for a simple array

佐手、 提交于 2019-12-11 06:21:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!