2

对于以下代码(参见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";
} 

结果是,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 之类的索引放入此模型中?我想要整数索引来引用数组中的位置,而不是需要重新计算的这个位置的值。

更新

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

4

2 回答 2

9

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

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

我已经更新了 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;
}
于 2013-10-09T12:53:05.367 回答
2

类似的东西?

<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];
}

演示Fiddle

于 2013-10-09T12:26:03.437 回答