be-codified
be-codified

Reputation: 6124

AngularJS: selecting option from dropdown menu

Here is my code:

<select class="form-control" name="author" ng-options="author as author.fullname for author in authors" ng-model="author" ng-required="true"></select>

How would I change selected value from controller?

Upvotes: 0

Views: 117

Answers (2)

Doug E Fresh
Doug E Fresh

Reputation: 840

Angular works on "2-way binding". ng-model="author" binds your dropdown to $scope.author so a change in either the dropdown or the controller will reflect on both places, hence the binding. So from your ng-options I'm assuming you have an array called authors of type author so in your controller simply

$scope.author = $scope.authors[0];

Remember that in the controller you need the $scope. before the variable and in the html ng-model or other ng directives you do not need the $scope. prefix

Upvotes: 3

Tom
Tom

Reputation: 7740

Simply set the $scope.author to whatever author you want, for example:

$scope.author = $scope.authors[2];

Here is an example jsBin

Or look up the author some how (by name, id?) and set the $scope.author or whatever to that value.

Upvotes: 3

Related Questions