Display value in html <select> from sessionStorage

Viewed 48

I have the folllowing select that allows a user to choose a color.

<select id="colorChoice" class="form-control text-center" ng-model="colorToSet" ng-change="setColor(colorToSet)">
  <option class="dropdown-item" ng-repeat="color in colors" value="{{color}}">{{color}}</option>
</select>

As it is, the dropdown item is blank and when opened, the color options are showed. The user choose a color and this color is displayed on the dropdown item.

But when the page refreshes, that value does not remain displayed into the dropdown item.

I am now saving that value into the sessionStorage and I want to show it when page is refreshed.

$scope.colors = ['red', 'green', 'orange', 'blue'];

$scope.setColor = function(colorToSet) {
  sessionStorage.setItem("color", colorToSet);
}

enter image description here enter image description here

2 Answers

On page refresh, you just need to get the value back from sessionStorage and set it to your model colorToSet like:

$scope.colorToSet = sessionStorage.getItem("color") || '';

try using

sessionStorage.getItem("colorToSet")

let color = sessionStorage.getItem("color") || '';

and set value to color

Related