把一个指数与NG选项一款型号为一个简单的数组 [英] Put an index to a model with ng-options for a simple array

查看:123
本文介绍了把一个指数与NG选项一款型号为一个简单的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关以下code(请参阅小提琴):

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

其结果是,HTML:

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>

...这是完全正常的。然而,AMPM被放入 AMPM 模式。是否有可能将像0或1的索引,这种模式?我希望有这指的位置在阵列整数索引,但不是在这个位置,这将需要重新计算的值。

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

更新

有没有一种方法,以避免造成对数组?

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.

本使用 NG-选项 的语法选择作为标签的数组值详见该角文档:<一href=\"http://docs.angularjs.org/api/ng.directive:select\">http://docs.angularjs.org/api/ng.directive:select

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

我已经更新了的jsfiddle:

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选项一款型号为一个简单的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆