How to select a value from an <option> by Angularjs

Asked

Viewed 1,390 times

3

Well, I do an interaction to get the options, and I want to select the first option

             <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 have tried using ng-select, but it was unsuccessful.

1 answer

1

First remove the select as of 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>

Then on his controller set the model (in the case of, 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
};

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.