calthoff
calthoff

Reputation: 386

Angular Select an option with ng-model

I am using AngularJS, and I cannot figure out how to select an option in a dropdown menu that contains ng-model.

For example, this selects an option:

<select name="type" class="input">
      <option value="article">Article</option>
      <option ng-selected="true" value="book">Book</option>
      <option value="class">Class</option>
</select> 

But as soon as I add ng-model, the option with ng-selected is no longer selected:

 <select name="type" class="input" ng-model="select">
      <option value="article">Article</option>
      <option ng-selected="true" value="book">Book</option>
      <option value="class">Class</option>
  </select>

Any idea how to fix this?

Upvotes: 1

Views: 1208

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222582

You can use ng-init to set the initial value

DEMO

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) { 
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello AngularJS</title>
</head>

<body ng-controller="myCtrl">     
<select name="type" class="input" ng-init="select='book'" ng-model="select">
      <option value="article">Article</option>
      <option value="book">Book</option>
      <option value="class">Class</option>
  </select>
 <script src="https://code.angularjs.org/1.6.1/angular.js"></script>
 </body>
</html>

Upvotes: 1

user8193706
user8193706

Reputation: 2425

Have you tried using the value of select inside the controller. Just look at this :

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.select= "book";
});
</script>

Upvotes: 0

Related Questions