Reputation: 191
I have tried everything in the book. I just cant get option 1 value="1" User to be preselected. I am using angular website. If I remove ng-model="type" it gets preselected. but just cant get it working with ng-model="type" in it.
<div class="form-group">
<select name="type" id="type" class="form-control" ng-model="type">
<option value="1" selected="selected">User</option>
<option>Broadcasters</option>
</select>
</div>
Upvotes: 2
Views: 6098
Reputation: 48968
Use the ng-value directive for numerical option values:
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app ng-init="type=1">
<div class="form-group">
<select name="type" id="type" class="form-control" ng-model="type">
<option ng-value="1">User</option>
<option ng-value="2">Broadcasters</option>
</select>
<p>type = {{type}}</p>
</div>
</body>
Upvotes: 1
Reputation: 528
Simple solution: You can use ng-selected directive
<div class="form-group">
<select name="type" id="type" class="form-control" ng-model="type">
<option value="1" ng-selected="true">User</option>
<option>Broadcasters</option>
</select>
</div>
It happens because you pass Number to ng-model, instead input has string as value. Also it will work without ng-selected directive if you will pass String to ng-model.
Better to use: ng-options
<select ng-options="type as type.label for type in types" ng-model="currentType"></select>
$scope.types = [{
id: 1,
label: 'User'
}, {
id: 2,
label: 'Broadcasters'
}];
$scope.currentType = $scope.types[0]; //default type
Upvotes: 1
Reputation: 222722
You can use ng-model with ng-init to set the default selected value,
<select name="type" ng-model="selected" ng-init="selected='1'" id="type" class="form-control" ng-model="type">
DEMO
var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
});
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="AppCtrl">
<div class="form-group">
<select name="type" ng-model="selected" ng-init="selected='1'" id="type" class="form-control" ng-model="type">
<option value="1" >User</option>
<option>Broadcasters</option>
</select>
</div>
</div>
</body>
</html>
Upvotes: 0