0

I have gone through few(1,2, others) posts on SO about ngOptions and the documentation too. I am getting the select working properly but there is a problem in selecting the default value on first launch. Once I change it, everything works perfect. As this questoin rightly answers, the angularjs creates an empty option when the model value is not found in the provided options, but my value 3 exists well within the provided range.

Below is the sList object as I receive from server, but the select always renders non-selected with empty choice, while there exists a valid value in the model. It might be because of difference between '3' and 3, but am not sure if and how that makes difference.

In JS:

sModel = 3;
sList = {0: "NONE", 1: "LS", 2: "SS", 3: "CR"};


<select ng-model="sModel" ng-options="key as val for (key,val) in sList track by key"></select>

Rendered Select Box:

<select ng-model="sModel" ng-options="key as val for (key,val) in sList track by key" class="ng-pristine ng-valid ng-not-empty ng-touched" aria-invalid="false" style="">
<option value="?" selected="selected"></option>
<option label="NONE" value="0">NONE</option>
<option label="LS" value="1">LS</option>
<option label="SS" value="2">SS</option>
<option label="CR" value="3">CR</option>
</select>

I know most such questions are protected for duplicate answers, but I could not find the exact problem I am encountering, so it might be very basic thing I am missing.

Any help to let understand what exactly am I doing wrong here is highly appreciated.

Community
  • 1
  • 1
user1242321
  • 1,578
  • 2
  • 18
  • 30

1 Answers1

0

var myapp = angular.module('app', []);
myapp.controller('Ctrl', function ($scope) {
  var vm = this;
  vm.sModel = "3";
    vm.sList = {0: "NONE", 1: "LS", 2: "SS", 3: "CR"};
   
      
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl as vm">
<select ng-model="vm.sModel" ng-options="key as val for (key,val) in vm.sList"></select>
</div>

try this

sModel = "3";
sList = {0: "NONE", 1: "LS", 2: "SS", 3: "CR"};
Hadi J
  • 16,989
  • 4
  • 36
  • 62
  • Hi @hadiJZ : The value of sModel is being received by server and I am looking for a clean way without changing the value. Because when I send the selected option value to server, it is rightly sending 3, not '3' so I am not sure if that should be the way to resolve this even if that gets it working. – user1242321 Mar 11 '16 at 04:25