对于以下代码(请参阅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之类的索引放入此模型中?我想要有整数索引来引用数组中的位置,但不是这个位置需要重新计算的值。
更新
有没有办法避免创建一对数组?
答案 0 :(得分:7)
您可以将select设置为使用元素的索引作为模型。
这使用了ng-options
的{{1}}语法,详见Angular文档:http://docs.angularjs.org/api/ng.directive:select
我已经更新了jsFiddle:
HTML:
select as label for value in array
JS:
<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>
答案 1 :(得分: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