ng-options Default Value for Angular Dropdown

纵饮孤独 提交于 2019-12-12 03:36:24

问题


I have two dropdowns, one is dependent on the other. I originally had my code using ng-repeat but read that it is more efficient to use ng-options. However, in switching over, I can't use ng-selected for the default any longer.

I've looked at different methods of setting the default option in ng-options but they use either <option value="">Select Something Here</option> for a customized option or selecting straight from the dataset. However my value will be changing.

Here is a plunker missing the default using ng-option:

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

I have the controller like so:

      <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>

and an example of my data:

$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"
      }
    ];

I had it working when I used ng-options="opt.DefCom as opt.DefCom for opt in acct_info | filter:{Req:'MUST'}:true" as seen here: http://plnkr.co/edit/vyJuZDM7OvE5knsfHln7?p=preview but I changed it in order to get the associated bindings. If anyone has more insight to the way ng-options works that would be very helpful.


回答1:


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

The value bound to ng-model="defcom" will be an entire object opt. To set a default, you need to assign an entire object to $scope.defcom . e.g. $scope.defCom = $scope.acct_info[2];

With your current data, this will make the default

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

Of course, you may not always know what your data will be so you may want to write some functions to get accounts or customers by one of their properties.

$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

Having a look at the Arguments section of the documentation may help



来源:https://stackoverflow.com/questions/36583813/ng-options-default-value-for-angular-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!