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

AngularJS ng-repeat内动态select默认值问题:如何配置ngModel?

解决AngularJS表格中Select默认选中与产品typeId匹配选项的问题

我来帮你搞定这个问题~核心问题出在你的ng-model绑定的是一个全局变量slideshowSelect,所有循环生成的select都会共用这个变量,既没法独立保存每个产品的选择,也没法默认匹配每个产品的typeId。

正确的ngModel绑定方式

你需要把ng-model绑定到当前遍历的产品对象x的typeId属性(也就是和slideshowsList里y.id对应的那个字段)。这样每个select都会独立关联自己行的产品类型ID,AngularJS会自动根据track by y.id的规则,匹配选中y.id等于x.typeId的选项。

修改后的代码

<tbody>
  <tr ng-repeat="x in screensList">
    <th scope="row"> {{x.pantalla}} </th>
    <td> {{x.description}} </td>
    <td>
      <!-- 把ngModel绑定到x.typeId,确保和slideshowsList里的y.id对应 -->
      <select class="form-control" 
              ng-model="x.typeId" 
              ng-options="y.title for y in slideshowsList track by y.id">
      </select>
    </td>
    <td class="text-right">
      <button type="button" 
              ng-click="deleteService($event)" 
              serviceId="{{x.id}}" 
              class="btn btn-danger btn-sm">
        Eliminar
      </button>
    </td>
  </tr>
</tbody>

补充说明

  • 如果你的产品对象x里存储的不是typeId,而是整个slideshow对象(比如x.slideshow),那可以调整ng-options去掉track by y.id,然后把ng-model绑定到x.slideshow,这样Angular会通过对象引用匹配默认选项。
  • 确保slideshowsList里的每个y.id和x.typeId的类型一致(比如都是数字或者都是字符串),否则可能会出现匹配失败的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:25:08