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

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条的情况,可以先把过滤后的结果存为临时变量,再监听长度变化实现自动选中:

  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>
  1. 新增监听逻辑:
$scope.$watch('filteredCustomers.length', function(newLength) {
    if (newLength === 1) {
        $scope.relatedTo = $scope.filteredCustomers[0].CUSTCODE;
    }
});

内容的提问来源于stack exchange,提问作者Joshua Alforque

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:24:02