AngularJS中使用ng-options的动态下拉框单选项时设置默认选中值问题
AngularJS单选项自动选中解决方案
方案1:针对原始选项数组判断(无动态过滤场景)
你在ng-options中配置的选中值为c.CUSTCODE,和ng-modelrelatedTo绑定,所以只需要在获取到后端返回的客户列表后,判断数组长度,长度为1时直接给relatedTo赋值即可,修改后的请求代码如下:
$http.post('commandCenter.aspx/allCustomer', {}).then( function onSuccess(response) { $scope.customers = JSON.parse(response.data.d); // 新增自动选中逻辑 if ($scope.customers.length === 1) { $scope.relatedTo = $scope.customers[0].CUSTCODE; } console.log($scope.customers); }, function onError(response) { console.log('error !!! '); });
方案2:针对带filter过滤的场景
如果存在code过滤条件,可能出现原始数组长度大于1,但过滤后只剩1条的情况,可以先把过滤后的结果存为临时变量,再监听长度变化实现自动选中:
- 先修改HTML代码,将过滤后的结果赋值给临时变量
filteredCustomers:
<select class="form-control form" ng-model="relatedTo" style="height: 40px;" ng-options="c.CUSTCODE as c.CUSTNAME + ' - ' + c.CUSTCODE for c in filteredCustomers = (customers | filter:code)" > </select> <span style="color:red" ng-show="type === 9 || type !== 9"></span>
- 新增监听逻辑:
$scope.$watch('filteredCustomers.length', function(newLength) { if (newLength === 1) { $scope.relatedTo = $scope.filteredCustomers[0].CUSTCODE; } });
内容的提问来源于stack exchange,提问作者Joshua Alforque
相关产品推荐
相关产品推荐

