Search code examples
angularjsng-options

selected value not works in the first time in ng-option when using a simple array


<script type='text/javascript' src='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js'></script>

<div data-ng-app="app" data-ng-controller="exCtrl">
    <select data-ng-model="selectedValue"
        ng-options="key as value for (key , value) in dataset">
        <option></option>
    </select>
   {{selectedValue}}
</div>

script

<script>
    var app = angular.module("app",[]);
    app.controller("exCtrl",function($scope) {
        $scope.dataset = {1:"one", 2:"two", 3:"three"};
        $scope.selectedValue = 1;
    });
</script>

selected value is not selected in the select element initially but the selected value is there, But it works fine after we select one value from the select element. why ? and how do i overcome this?

Note: I cant change the array structure.


Solution

  • In you code you use a literal object, it works like a key/value array but when you declare {1:"one".. in fact the key's not the integer 1 but the string "1".

    If you want to initialize your ng-option directive with an object as a source you must use a string.

     $scope.selectedValue = "1";