为简单数组的模型添加索引

为简单数组的模型添加索引

本文介绍了使用 ng-options 为简单数组的模型添加索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码(请参阅fiddle):

HTML:

<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>上午/下午:{{ampm}}

JS:

function MyCtrl($scope) {$scope.ampm = "AM";}

结果是,HTML:

<option value="0" selected="selected">AM</option><option value="1">PM</option></选择>

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

更新

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

解决方案

可以设置select使用元素的索引作为模型.

这使用 select as label for value in arrayng-options 语法,详见 Angular 文档:http://docs.angularjs.org/api/ng.directive:select

我已经更新了 jsFiddle:

http://jsfiddle.net/EyBVN/28/

HTML:

<选择ng-model="ampm"ng-options="options.indexOf(currOption) as currOption for currOption in options"></select>上午/下午:{{ampm}}

JS:

function MyCtrl($scope) {$scope.options = ['AM', 'PM'];$scope.ampm = 0;}

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?

解决方案

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

这篇关于使用 ng-options 为简单数组的模型添加索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:22