为简单数组提供带有 ng 选项的模型索引

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

本文关键字:选项 ng 模型 索引 简单 数组      更新时间:2023-09-26

对于以下代码(请参阅小提琴(:

.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";
} 

结果是,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>

。这完全没问题。但是,'AM''PM'正在被放入ampm模型中。是否可以将像 0 或 1 这样的索引放入此模型中?我想要引用数组中位置的整数索引,而不是需要重新计算的该位置的值。

更新

有没有办法避免创建配对数组?

您可以将选择设置为使用元素的索引作为模型。

这使用 Angular 文档中详述的select as label for value in array ng-options语法:http://docs.angularjs.org/api/ng.directive:select

我已经更新了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;
}

类似的东西?

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

控制器

function MyCtrl($scope) {
    $scope.ampm = [{name: "AM",value: "0" },{name: "PM",value: "1" }];
    $scope.selectItem = $scope.ampm[0];
}

演示小提琴