I have a <select>
element in my html page. The <option>
s are given through a loop. The selected value is stored using a ng-model
. This data is now push to a database. The next time that page reloads I would like the the <select>
field to hold the previously selected option. Is there anyway to do it?
I have seen that ng-model
generally fills text fields on it own. I tried to do the same with <select>
-<option>
but it doesn't work
<select ng-model="option">
<option value = "" disabled selected>---Choose an Option--</option>
<option ng-repeat = "x in option" value="x">{{x}}</option>
</select>
When selecting from an array of primitives, use the ng-options
directive:
angular.module("app",[])
.controller("ctrl", function($scope) {
$scope.options=["hello","world",1,2,3];
//set previously selected option
$scope.option = "world";
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<select ng-model="option" ng-options="item for item in options">
<option value = "">---Choose an Option--</option>
</select>
<br>selected={{option}}
<body>
One can select using ng-repeat
with an array of objects, but not with an array of primitives. Under the hood, the <select>
directive annotates each option with tracking information. It can't annotate primitives.
For more information, see