简体   繁体   中英

How to have a default selected value for angularjs 1.5 programmatically

I want to add a "Select a bank" option in the dropdown. I Only want that option to be selected if there is more than 1 item in the list (banks). This is the code:

This is what I current have:

<select class="form-control" name="bankName" id="field_bankName"
        ng-model="vm.bankAccount.bankName"
        ng-options="banks as banks.description for banks in vm.items.banks track by banks.id"
        required>
  <option selected="selected" value="" disabled="">Select a bank</option>
</select>

However, I want the only (first) option in the list to be selected if the list only has 1 item on it.

I tried to do multiple things, but none seem to work, from having an ng-selected with a banks.length > 1 expression inside however I Cannot add an expression to the ng-options for every "option" that is something like ng-selected="banks.length == 1" .

Can you please point me to the best approach for solving this issue?

Initialize vm.bankAccount.bankName in the controller:

if (vm.banks.length == 1) {
    vm.bankAccount.bankName = vm.banks[0];
} else {
    vm.bankAccount.bankName = null;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM