Shaffanhoon Shaffanhoon - 5 months ago 18
AngularJS Question

Angular selected option ignoring first array value

I am attempting to use

to remember the user's selection and set the selected option accordingly on their next login.

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
on load
Index is 0

index of
on load
Index is 1

What am I doing wrong?


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

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)


I recommend you to use ngOptions.

See it working:

(function() {
  'use strict';

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

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

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

  <script src=""></script>
  <link rel="stylesheet" href="">

<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>
    <pre ng-bind="selectedOption"></pre>