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

如何在AngularJS中通过编程方式设置下拉选择框选中项?

解决AngularJS下拉框不显示当前选中值的问题

嘿,我来帮你搞定这个下拉框不显示选中值的问题~ 看了你的代码,核心问题出在**ng-model的值和ng-options的匹配类型不对应**,下面给你两种靠谱的解决思路:

思路一:让ng-model匹配对应的对象

你现在用ng-init="test=2"给test赋值了一个数字,但你的ng-options用了track by c.id,这时候Angular会期望test是categories数组里id为2的那个完整对象,而不是单纯的数字ID,所以下拉框找不到匹配项,自然就没显示。

具体做法:

  1. 推荐在控制器里初始化test(尽量别用ng-init,控制器才是处理数据的正确地方):
    // 假设你的分类数据长这样
    $scope.categories = [
      {id: 1, name: '分类1'},
      {id: 2, name: '分类2'},
      {id: 3, name: '分类3'}
    ];
    // 找到id为2的对象赋值给test
    $scope.test = $scope.categories.find(item => item.id === 2);
    
  2. 如果一定要用ng-init(不推荐),可以这样写:
    <div class="input-field col s12" ng-init="test = categories.find(c => c.id === 2)">
      <label for="item_code" class="active">Category</label>
      <select ng-model="test" ng-options="c.name for c in categories track by c.id" >
      </select>
      <p>This is the value {{test}}</p>
    </div>
    

思路二:调整ng-options,让它绑定ID值

如果你希望test直接绑定数字ID(比如保持test=2),那可以修改ng-options的写法,把选项的值绑定到c.id,去掉track by:

<div class="input-field col s12" ng-init="test=2">
  <label for="item_code" class="active">Category</label>
  <select ng-model="test" ng-options="c.id as c.name for c in categories" >
  </select>
  <p>This is the value {{test}}</p>
</div>

这样test=2就会直接匹配id为2的选项,下拉框就能正确显示选中值了。

额外注意:如果你用了Materialize CSS

因为Materialize会把原生的select替换成自定义DOM结构,所以你需要在数据加载完成后手动初始化下拉框组件,不然可能还是不显示。可以在控制器里加这段代码:

$timeout(function() {
  $('select').formSelect();
});

(记得要注入$timeout服务哦)如果你的categories是异步加载的,要确保在数据返回后再调用formSelect()。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:50:38