AngularJs and <select>: Default selected options are removed AngularJs and <select>: Default selected options are removed angularjs angularjs

AngularJs and <select>: Default selected options are removed


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.


By adding option with empty value to select and initializing selectedColors to empty string(ng-init="selectedColors=''"), we can see 'select Color' option on top instead of having first color to be selected defaultly:

<div><select id="myselection" ng-init="selectedColors=''" ng-model="selectedColors">    <option value="">Select Color</option>    <option value="1">Red</option>    <option value="2">Blue</option>    <option value="3">Green</option></select><div>Selected Colors: {{selectedColors }}</div>

Try it on Fiddle http://jsfiddle.net/CodecPM/qxyckf7u/