html5 – How to select a value from one<option> by AngularJS

Question:

Well, I do an iteration to get the options, and I want the first option to be selected

             <select class="form-control" 
                      name="accounts"
                      ng-model="vm.deposit.account"
                      ng-options="account.account as account.agency for account in vm.accounts"
                      required>
              </select>

My intention is to try the 'Selected' type. I've tried using ng-select, but it was unsuccessful.

Answer:

First remove the select as from the ng-options expression :

<select class="form-control" name="accounts" 
    ng-model="vm.deposit.account" 
    ng-options="account.agency for account in vm.accounts" 
    required=""></select>

Then, in your controller set the model (in this case, vm.deposit.account ) with value that should come as selected by default:

$scope.vm.deposit = {
    account: $scope.vm.accounts[0] // o primeiro valor do array
};

Complete example:

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope',
    function($scope) {
      $scope.vm = {
        accounts: [{
          agency: 'Agency 1',
          account: 'a1'
        }, {
          agency: 'Agency 2',
          account: 'a2'
        }, {
          agency: 'Agency 3',
          account: 'a3'
        }]
      };

      $scope.vm.deposit = {
        account: $scope.vm.accounts[1] // o segundo valor do array
      };
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="selectExample">
  <div ng-controller="ExampleController">
    <select class="form-control" name="accounts" ng-model="vm.deposit.account" ng-options="account.agency for account in vm.accounts" required=""></select>
  </div>
</div>

Full online example.

Scroll to Top