NG选项与简单的数组初始化 [英] ng-options with simple array init

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

问题描述

我是一个有点困惑与角度和 NG-选项

I'm a little bit confused with Angular and ng-options.

我有一个简单的数组,我想初始化一个选择它。但是,我想那期权价值=标签。

I have a simple array and I want to init a select with it. But, I want that options value = label.

$scope.options = ['var1', 'var2', 'var3'];

HTML

<select ng-model="myselect" ng-options="o for o in options"></select>

我得到什么:

<option value="0">var1</option>
<option value="1">var2</option>
<option value="2">var3</option>

我要什么:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

所以,我想:

<select ng-model="myselect2" ng-init=0 ng-options="options[k] as v for (k,v) in options"></select>

<select ng-model="myselect3" ng-init=0 ng-options="b as b for b in options"></select>

(但没有奏效。)

(But it didn’t work.)

我的表单提交外部,这就是为什么我需要'VAR1'作为值,而不是0。

My form is submitted externally, which is why I need 'var1' as the value instead of 0.

推荐答案

您其实是有它正确的在你的第三次尝试。

You actually had it correct in your third attempt.

 <select ng-model="myselect" ng-options="o as o for o in options"></select>

在这里看到一个工作的例子:
<一href=\"http://plnkr.co/edit/xEERH2zDQ5mPXt9qCl6k?p=$p$pview\">http://plnkr.co/edit/xEERH2zDQ5mPXt9qCl6k?p=$p$pview

诀窍是,AngularJS写入键作为数字从0到n反正和更新模型时转换回来。

The trick is that AngularJS writes the keys as numbers from 0 to n anyway, and translates back when updating the model.

其结果是,在HTML看起来不正确,但该模型将选择值时仍可以正确地设置。的(即。AngularJS会转化'0'回'VAR1')

As a result, the HTML will look incorrect but the model will still be set properly when choosing a value. (i.e. AngularJS will translate '0' back to 'var1')

由Epokk该解决方案也适用,但是如果你在加载数据不同步您可能会发现它并不总是正确更新。当范围变更使用ngOptions将正确刷新。

The solution by Epokk also works, however if you're loading data asynchronously you might find it doesn't always update correctly. Using ngOptions will correctly refresh when the scope changes.

这篇关于NG选项与简单的数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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