如何使由AngularJS生成的选择列表中的preselection? [英] How to make a preselection for a select list generated by AngularJS?

查看:121
本文介绍了如何使由AngularJS生成的选择列表中的preselection?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <选择NG模型=team.captainNG选项=player.name在team.players播放器>< /选择>

这正确地创建了一个选择列表中选择队长。但是,默认的空白选项。怎能preSELECT从列表中呢?

的第一个球员

 <选择NG模型=team.captainNG选项=player.name在team.players球员级=NG-原始NG-有效&GT ;
  <期权价值=0>约翰和LT; /选项>
  <期权价值=1>鲍比< /选项>
< /选择>

我尝试添加 NG-的init =team.captain ='0'但这并没有帮助。

更新显然,这是因为


  

吴模型引用的值不会在一组传递到NG-选项选项存在。


来源:<一个href=\"http://stackoverflow.com/questions/12654631/why-does-angularjs-include-an-empty-option-in-select?rq=1\">Why不angularjs包括选择一个空的选项

然而,问题仍然存在,为什么采用NG-init没有工作?

 &LT;选择NG-的init =team.captain ='0'NG模型=team.captainNG选项=player.name在队的球员。玩家&GT;&LT; /选择&GT;


解决方案

下面是什么工作:

 &LT;选择NG-的init =team.captain = team.players [0]
        NG-模式=team.captain
        NG-选项=player.name在team.players播放器&GT;&LT; /选择&GT;

和什么不工作:

  NG-的init =team.captain ='0'
NG-的init =team.captain ='约翰'

我的猜测是,角超出值或标签的简单比较。它可能比较对象的引用。

<select ng-model="team.captain" ng-options="player.name for player in team.players"></select>

This correctly creates a select list to choose the team captain. However, by default a blank option is selected. How can we preselect the first player from the list instead?

<select ng-model="team.captain" ng-options="player.name for player in team.players" class="ng-pristine ng-valid">
  <option value="0">John</option>
  <option value="1">Bobby</option>
</select>

I tried adding ng-init="team.captain='0'" but that didn't help.

Update Apparently this happens because

a value referenced by ng-model doesn't exist in a set of options passed to ng-options.

Source: Why does angularjs include an empty option in select

However, the question still remains why using ng-init doesn't work?

<select ng-init="team.captain='0'" ng-model="team.captain" ng-options="player.name for player in team.players"></select>

解决方案

Here's what worked:

<select ng-init="team.captain=team.players[0]" 
        ng-model="team.captain" 
        ng-options="player.name for player in team.players"></select>

And what didn't work:

ng-init="team.captain='0'"
ng-init="team.captain='John'"

My guess is that Angular goes beyond simple comparison of values or labels. It probably compares object references.

这篇关于如何使由AngularJS生成的选择列表中的preselection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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