I expect the following code to render a drop down list with the third option selected by default. However, when I bind the select with angularjs, the default selection disappears. Any thought?
var myApp = angular.module('myApp', []);
...
<div>
<select id="myselection" ng-model="selectedColors">
<option value="1" >Red</option>
<option value="2">Blue</option>
<option value="3" selected="selected">Green</option>
</select>
<div>
Selected Colors: {{selectedColors }}
</div>
</div>
Here's a working example: http://jsfiddle.net/TXPJZ/134/
Thanks!
Use ng-init to set default value for ng-options .
The select directive is used together with ngModel to provide data-binding between the scope and the <select> control (including setting default values). It also handles dynamic <option> elements, which can be added using the ngRepeat or ngOptions directives.
The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options . This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.
The easiest way to fix your implementation is to use ng-init
.
<div>
<select id="myselection" ng-init="selectedColors=3" ng-model="selectedColors">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
</select>
<div>Selected Colors: {{selectedColors }}</div>
</div>
Try it on FIDDLE.
Angular overrides the "selected" property when you bind the select to a model. If you inspect the rendered DOM you will find that a new item has been added:
<option value="? undefined:undefined ?"></option>
In order to automatically select the third option you need to pre-populate the model in scope. There are a few ways to do this, including wrapping the select in a controller:
<div ng-controller="MyCtrl">
<select id="myselection" ng-model="selectedColors">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Green</option>
</select>
<div>Selected Colors: {{selectedColors }}</div>
And then defining that model in the controller.
var myApp = angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.selectedColors = 2;
}]);
Here's a running example.
http://jsfiddle.net/93926/
Alternatively, you could just initialize it using ng-init such as in this example:
<div ng-init="selectedColors=3">
http://jsfiddle.net/9JxqA/1/
EDIT: Removed the selected property in the first example, it's no longer needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With