Wisely Wong
Wisely Wong

Reputation: 380

ng-model in select box with default value is empty

I am trying to use ng-model to get value from the selection tag with Angular js. However, when I render this code, the selected box is empty when the page finished loading. I tried to set the first option to be selected, but that doesn't work. I tried selected="selected" but doesn't work. I also tried other methods mentioned in documentation about ng-option but it doesn't seem to help. I NEED the ng-model value in order for other parts of my page to work.

<select id="teamSelection" ng-model="teamSelected"> <option value="All" selected>All</option> <option value="1">A</option> <option value="2)">B</option> <option value="3">C</option> <option value="4">D</option> </select>

Upvotes: 4

Views: 2281

Answers (2)

bobleujr
bobleujr

Reputation: 1176

Set you $scope.teamSelected = 3 (index of the desired object) for example, and it should work fine like in this codepen

Upvotes: 2

Ming Huang
Ming Huang

Reputation: 1370

I just ran into the same problem earlier this week. The fix is actually simpler than I thought. You can just add a ng-init="teamSelected='All'" as an attribute to your select tag:

<select id="teamSelection" ng-model="teamSelected" ng-init="teamSelected='All'"> <option value="All" selected>All</option> <option value="1">A</option> <option value="2)">B</option> <option value="3">C</option> <option value="4">D</option> </select>

Upvotes: 6

Related Questions