You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS中ng-repeat内ng-selected不生效问题求助

解决AngularJS中ng-repeat内根据值选中

我来帮你搞定这个select选项选中的问题~首先得指出你当前代码里的两个关键问题:

  • ng-selected 是Angular的指令,它的表达式本身就在Angular的上下文里,不需要用{{}}插值,直接引用变量就行;
  • 用this.value来对比并不靠谱,应该直接把option的value值和x.nivel做相等判断。

修正后的基础写法

把你的代码改成这样就能正常工作了:

<li ng-repeat="x in inscritos | orderBy:'nome'">
  <select>
    <option ng-selected="x.nivel === 'Iniciante'" value="Iniciante">Iniciante</option>
    <option ng-selected="x.nivel === 'Intermediário'" value="Intermediário">Intermediário</option>
    <option ng-selected="x.nivel === 'Avançado'" value="Avançado">Avançado</option>
  </select>
</li>

原理很简单:ng-selected接受一个布尔表达式,当x.nivel和当前option的value完全相等时,表达式返回true,这个option就会被自动选中。

更优雅的Angular风格写法

如果你的选项是固定的,推荐用ng-options来生成选项,配合ng-model绑定,这样不需要手动写每个ng-selected,代码更简洁且不易出错:

<li ng-repeat="x in inscritos | orderBy:'nome'">
  <select ng-model="x.nivel" ng-options="nivel for nivel in ['Iniciante', 'Intermediário', 'Avançado']"></select>
</li>

这里ng-model直接绑定x.nivel,Angular会自动根据x.nivel的值匹配对应的选项并选中,同时用户修改选择时,x.nivel的值也会自动更新,完美适配管理页面的需求。

内容的提问来源于stack exchange,提问作者jeanm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:37:17