ng-options Angular Dropdown的默认值

时间:2016-04-12 20:51:07

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

我有两个下拉菜单,一个依赖于另一个。我最初使用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的工作方式有更多的了解,那将非常有用。

1 个答案:

答案 0 :(得分: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参数部分可能会有所帮助