How to select a value from an option by AngularJS

3

Well, I make an interaction 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 intent is to try a 'Selected' type. I've already tried using ng-select, but it was unsuccessful.

    
asked by anonymous 25.05.2015 / 20:04

1 answer

1

First remove select as from expression ng-options :

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

Next, in its% with the template (in this case, controller ) 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><divng-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>

Complete online sample.

    
25.05.2015 / 21:05