带有简单数组初始化的 ng-options [英] ng-options with simple array init

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

问题描述

我对 Angular 和 ng-options 有点困惑.

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>

(但没用.)

我的表单是从外部提交的,这就是为什么我需要 '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>

在此处查看工作示例:http://plnkr.co/edit/xEERH2zDQ5mPXt9qCl6k?p=preview

诀窍是 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-options的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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