【问题标题】:ng-options Default Value for Angular Dropdownng-options Angular 下拉菜单的默认值
【发布时间】:2026-02-04 14:50:01
【问题描述】:

我有两个下拉菜单,一个依赖于另一个。我最初使用 ng-repeat 编写代码,但读到使用 ng-options 更有效。但是,在切换时,我不能再使用 ng-selected 作为默认值。

我查看了在 ng-options 中设置默认选项的不同方法,但他们使用 <option value="">Select Something Here</option> 自定义选项或直接从数据集中选择。但是我的价值会发生变化。

这是一个使用 ng-option 缺少默认值的 plunker:

http://plnkr.co/edit/VwqrsR38GOFubW8i46FJ?p=preview

我有这样的控制器:

      <select ng-model="defcom"
        ng-options="opt as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" >
      </select>
       <p>Hello {{ defcom.AcctName }}</p>

以及我的数据示例:

$scope.acct_info = [
      {
        "Req": "MUST",
        "DefCom": "1",
        "AcctName": "ThisName"
      },
      {
        "Req": "NoMUST",
        "DefCom": "5",
        "AcctName": "ThisName2"
      },
      {
        "Req": "MUST",
        "DefCom": "4",
        "AcctName": "ThisName3"
      },
      {
        "Req": "MUST",
        "DefCom": "7",
        "AcctName": "ThisName4"
      }
    ];

当我使用ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" 时,它可以正常工作,如下所示:http://plnkr.co/edit/vyJuZDM7OvE5knsfHln7?p=preview 但我更改了它以获取关联的绑定。如果有人对 ng-options 的工作方式有更深入的了解,那将非常有帮助。

【问题讨论】:

    标签: angularjs data-binding drop-down-menu default ng-options


    【解决方案1】:

    ng-options="opt as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true"

    绑定到ng-model="defcom" 的值将是整个对象opt。要设置默认值,您需要将整个对象分配给 $scope.defcom 。例如$scope.defCom = $scope.acct_info[2];

    使用您当前的数据,这将成为默认值

    {
      "Req": "MUST",
      "DefCom": "4",
      "AcctName": "ThisName3"
    }
    

    当然,您可能并不总是知道您的数据是什么,因此您可能需要编写一些函数来通过其属性之一获取帐户或客户。

    $scope.defcom = getAccountByDefCom("4");
    $scope.defcust = getCustomer("3");
    
    function getAccountByDefCom(defcom) {
      for (var i = 0; i < $scope.acct_info.length; i++) {
        if ($scope.acct_info[i].DefCom === defcom) {
          return $scope.acct_info[i];
        }
      }
    }
    
    function getCustomer(number) {
      for (var i = 0; i < $scope.cust_info.length; i++) {
        if ($scope.cust_info[i].Customer === number) {
          return $scope.cust_info[i];
        }
      }
    }
    

    Example Plunker

    查看documentation参数部分可能会有所帮助

    【讨论】: