Reputation: 12535
I have the following Angular code in my HTML file.
I have a drop-down box with two fixed choices: A
and B
.
The user must select either A
or B
. It cannot be left blank.
I would like the default selection to be A
. How can I do it?
The following code starts off with an empty drop-down box. I don't want that. I want A
to be pre-selected.
<div ng-controller="MyController as myCtrl">
<select ng-model="myCtrl.param1">
<option value="a" selected>A</option>
<option value="b">B</option>
</select><br/>
<button ng-click="myCtrl.submit()">submit</button>
</div>
Upvotes: 2
Views: 2460
Reputation: 2060
The following illustrates the ways, by which one can do it:
Option 1: (by adding ng-selected="true"
)
HTML:
<div ng-app="app" ng-controller="MyController as myCtrl">
<select ng-model="myCtrl.param1">
<option value="a" ng-selected="true">A</option>
<option value="b">B</option>
</select><br />
<button ng-click="myCtrl.submit()">submit</button>
</div>
JS:
var app = angular.module('app', []);
app.controller('MyController', function ($scope) {
var myCtrl = this;
myCtrl.submit = function () {
/*..*/
}
$scope = myCtrl;
});
Option 2: (by setting the variable
in the controller
)
HTML:
<div ng-app="app" ng-controller="MyController as myCtrl">
<select ng-model="myCtrl.param1">
<option value="a">A</option>
<option value="b">B</option>
</select><br />
<button ng-click="myCtrl.submit()">submit</button>
</div>
JS:
var app = angular.module('app', []);
app.controller('MyController', function ($scope) {
var myCtrl = this;
myCtrl.submit = function () {
}
myCtrl.param1 = "a";
$scope = myCtrl;
});
If you do not want to pre-select any, but show a label then ->
Option 3: (by just showing a 'Select' label - no pre-select in this case)
HTML:
<div ng-app="app" ng-controller="MyController as myCtrl">
<select ng-model="myCtrl.param1">
<option value="">Select</option>
<option value="a">A</option>
<option value="b">B</option>
</select><br />
<button ng-click="myCtrl.submit()">submit</button>
</div>
JS:
var app = angular.module('app', []);
app.controller('MyController', function ($scope) {
var myCtrl = this;
myCtrl.submit = function () {
}
$scope = myCtrl;
});
Upvotes: 2
Reputation: 337
You need to use ng-selected and based on key you can keep selected or not selected items for e.g
<md-select ng-model="sms.from" ng-change="getSelectedValue(sms.from, 'from')">
<md-option ng-repeat="(i,item) in fromNumber" ng-value="item" ng-selected="i == 0 ? true:false">{{ item }}</md-option>
</md-select>
Upvotes: 2
Reputation: 214
You can declare a variable in your controller as follows:
$scope.myCtrl.param1 = 'A';
Working fiddle: https://jsfiddle.net/n9tL7cdr/2/
Upvotes: 3