如何设置AngularJS多选Select框默认选中ABC项?
解决AngularJS多选Select框默认选中“ABC”的问题
嘿,我来帮你搞定这个默认选中的需求~先提个小细节:你的HTML里ng-options用的是config.saleStatus,但控制器里定义的是$scope.saleStatus,这会导致选项加载不出来,得先把HTML里的数据源改成saleStatus哦。
接下来设置默认选中的核心点:因为是多选下拉框,绑定的ng-model必须是一个数组,而且要把你想默认选中的对象(也就是“ABC”那一项)放进这个数组里——AngularJS是通过对象引用来匹配选中项的。
修改后的完整代码:
控制器部分
$scope.saleStatus = [ {'id': 18, 'name': 'ABC'}, {'id': 19, 'name': 'DEF'}, {'id': 20, 'name': 'GHI'} ]; // 初始化默认选中数组,放入ABC对应的对象 $scope.selectedSaleStatus = [$scope.saleStatus[0]]; // 或者如果不想依赖数组索引,用find方法精准匹配: // $scope.selectedSaleStatus = [$scope.saleStatus.find(item => item.name === 'ABC')];
HTML部分
<select size="3" name="selectedSaleStatus[]" multiple ng-model="selectedSaleStatus" ng-options="type.name for type in saleStatus"></select>
额外说明
如果你的场景中,默认选中的对象可能不是来自$scope.saleStatus的同一个引用(比如从后端接口返回的数据),可以在ng-options里加上track by type.id,这样AngularJS会通过id来匹配选中项,而不是对象引用:
<select size="3" name="selectedSaleStatus[]" multiple ng-model="selectedSaleStatus" ng-options="type.name for type in saleStatus track by type.id"></select>
这种情况下,你可以直接把{id:18, name:'ABC'}放进selectedSaleStatus数组里,不用必须是原数组里的对象。
内容的提问来源于stack exchange,提问作者tom
相关产品推荐
相关产品推荐

