0

I am attempting to use localStorage to remember the user's selection and set the selected option accordingly on their next login.

The select options populate correctly as shown below.

populated options

When the index is 1 or above it works correctly, but whenever the first value is selected no value is selected by default on the next reload.

I have illustrated this below:

index of 0 on load Index is 0

index of 1 on load Index is 1

What am I doing wrong?

HTML

<select name="ipSelect" data-ng-model="selectedOption">
    <option ng-repeat="ip in adapters track by $index" data-ng-value="adapters.indexOf(ip)">{{ip}}</option>
 </select>

In the controller

ipcRenderer.on('device_ips_loaded', (event, adapters) => {
    let storedIndex = localStorage.getItem('defaultIp') || 0
    console.log('Adapters: ' + adapters)
    console.log('storedIndex: ' + storedIndex)
    $scope.adapters = adapters
    $scope.$apply(function() {
        $scope.selectedOption = adapters[storedIndex]
    })
    console.log('selectedOption: ' + $scope.selectedOption)
})
0

1 Answer 1

1

I recommend you to use ngOptions.

See it working:

(function() {
  'use strict';

  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.selectedOption = '1';
    $scope.adapters = ['25.91.79.201', '192.168.0.14']
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>

<body ng-controller="MainCtrl">
  <div class="col-md-12">
    <select class="form-control" ng-options="key as ip for (key, ip) in adapters" ng-model="selectedOption">
      <option value label="Select an adapter" hidden></option>
    </select>
    <pre ng-bind="selectedOption"></pre>
  </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.