I have an HTML <select>
tag:
Document type <select class="form-control" name="document_type" ng-model="document_type"
ng-options="opt as opt.label for opt in options" required>
I have saved an options
variable in the scope of my model:
$scope.options = [{
label : '',
value : ''
}, {
label : "ID card",
value : "ID card"
}, {
label : 'Passport',
value : 'Passport'
}, {
label : 'Driving license',
value : 'Driving license'
} ];
In this way I have the following field:
My target is to set the document_type
'variable' using the $scope
:
$scope.document_type = "Passport"
but it does not work and the <select>
field stays blank.
Your select is actually setting document_type
to an object with label
and value
properties, but you are trying to assign the default value as a string.
If you want document_type
to be a string rather than an object, you should change your ng-options
clause slightly. instead of opt as opt.label ...
use opt.value as opt.label ...
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.options = [{
label: '',
value: ''
}, {
label: "ID card",
value: "ID card"
}, {
label: 'Passport',
value: 'Passport'
}, {
label: 'Driving license',
value: 'Driving license'
}];
$scope.document_type="Passport";
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
Document type
<select class="form-control" name="document_type" ng-model="document_type"
ng-options="opt.value as opt.label for opt in options" required></select>
</body>
</html>