AngularJS - 对于选择值属性 [英] AngularJS - value attribute for select

查看:141
本文介绍了AngularJS - 对于选择值属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来源JSON数据是:

[
  {"name":"Alabama","code":"AL"},
  {"name":"Alaska","code":"AK"},
  {"name":"American Samoa","code":"AS"},
  ...
]

我尝试

ng-options="i.code as i.name for i in regions"

但我得到:

<option value="?" selected="selected"></option>
<option value="0">Alabama</option>
<option value="1">Alaska</option>
<option value="2">American Samoa</option>

而我期待得到:

<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AS">American Samoa</option>

那么,如何才能获得价值属性和摆脱?项目?

So, how to get value attributes and get rid of "?" item?

顺便说一句,如果我设置$ scope.regions到静态JSON而不是Ajax请求的结果,空的项目消失。

By the way, if I set the $scope.regions to a static JSON instead of AJAX request's result, the empty item disappears.

推荐答案

在第一次尝试我应该工作,但HTML不是我们所期望的。我添加了一个选项,以处理最初的无选择项的情况:

What you first tried should work, but the HTML is not what we would expect. I added an option to handle the initial "no item selected" case:

<select ng-options="region.code as region.name for region in regions" ng-model="region">
   <option style="display:none" value="">select a region</option>
</select>
<br>selected: {{region}}

以上生成此HTML:

The above generates this HTML:

<select ng-options="..." ng-model="region" class="...">
   <option style="display:none" value class>select a region</option>
   <option value="0">Alabama</option>
   <option value="1">Alaska</option>
   <option value="2">American Samoa</option>
</select>

小提琴

尽管角使用的值数值整数,该模型(即$ scope.region)将根据需要设置为AL,AK,或AS。 (该数值所使用的角度来查找当一个选项,从列表中选择正确的阵列项。)

Even though Angular uses numeric integers for the value, the model (i.e., $scope.region) will be set to AL, AK, or AS, as desired. (The numeric value is used by Angular to lookup the correct array entry when an option is selected from the list.)

这可能会产生混淆,当第一次学习如何角实现其选择指令。

This may be confusing when first learning how Angular implements its "select" directive.

这篇关于AngularJS - 对于选择值属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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