Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

like image 583
Wisely Wong Avatar asked Feb 10 '23 04:02

Wisely Wong


2 Answers

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>

like image 164
Ming Huang Avatar answered Feb 13 '23 11:02

Ming Huang


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

like image 42
bobleujr Avatar answered Feb 13 '23 11:02

bobleujr