AngularJS ui-select选中值不显示问题求助
问题诊断与解决
问题根源
你的ui-select组件选中后输入框不显示内容,核心原因是数据绑定不匹配:
<ui-select-choices>中使用repeat="t.Id as t in holdingTimePeriods | filter:$select.search",这会把t.Id作为选中值绑定到ng-model="search.HoldingTimePeriodId"- 但
<ui-select-match>里尝试访问$select.selected.Display,此时$select.selected是选中的ID(数值/字符串类型),并非完整的时间段对象,自然没有Display属性,导致无法显示内容。
解决方案
提供两种可行方案,可根据业务需求选择:
方案1:绑定完整对象(推荐)
这种方式更贴合ui-select的设计逻辑,也方便后续使用对象的其他属性:
- 修改HTML代码:
<ui-select name="procurementMode" ng-model="selectedHoldingTimePeriod" theme="select2" style="width: 100% !important;"> <ui-select-match allow-clear="true" placeholder="Select Holding Time Period" title="Select Holding Time Period"> {{$select.selected.Display}} </ui-select-match> <ui-select-choices refresh-delay="1" repeat="t in holdingTimePeriods | filter:$select.search"> {{t.Display}} </ui-select-choices> </ui-select>
- 在控制器中初始化绑定变量:
$scope.selectedHoldingTimePeriod = null;
- 提交数据时从对象中提取ID:
在$scope.gridConfig.getData函数里,替换原有的$scope.search.HoldingTimePeriodId赋值逻辑:
$scope.search.HoldingTimePeriodId = $scope.selectedHoldingTimePeriod ? $scope.selectedHoldingTimePeriod.Id.toString() : null;
方案2:保留绑定ID,修改显示逻辑
如果必须绑定ID而非完整对象,可通过ID匹配对应的显示值:
- 修改
<ui-select-match>部分:
<ui-select-match allow-clear="true" placeholder="Select Holding Time Period" title="Select Holding Time Period"> {{getHoldingTimePeriodDisplay(search.HoldingTimePeriodId)}} </ui-select-match>
- 在控制器中添加辅助函数:
$scope.getHoldingTimePeriodDisplay = function(id) { if (!id || !$scope.holdingTimePeriods) return ''; const period = $scope.holdingTimePeriods.find(t => t.Id == id); return period ? period.Display : ''; };
<ui-select-choices>的repeat逻辑保持不变即可。
额外注意事项
- 确保
holdingTimePeriods数组中的每个对象都包含Id和Display属性,且数据类型匹配(比如Id为数字时,绑定后是否转为字符串,需在匹配时注意) - 使用方案1时,清空选择后
selectedHoldingTimePeriod会变为null,提交数据时需处理空值情况
内容的提问来源于stack exchange,提问作者Abhishek Sharma
相关产品推荐
相关产品推荐

