Search code examples
javascriptjavaangularjshashmapng-options

AngularJS populating the ng-options options from Java Map. (Sorting issue)


so I sorted the map in Java and then passed into Javascript with new JSONObject(sortedMap);. This is already sorted by values. When passed in the Javascript file, if I hover the object in debug mode, I see

$scope.fruitList = {'AP' : 'Apple', 'GP' : 'Grape', 'LM' : 'Lemon'}; 

(sorry for the silly names.. just an example)

After this, in html file,

<select ng-model="fruit" ng-options="key as value for (key, value) in fruitList" >
    <option value="">----select----</option>
</select>

Because I want

<option value="">----select----</option>
<option value="AP">Apple</option>
<option value="GP">Grape</option>
<option value="LM">Lemon</option>

However, for some reason, the order is messed up when it comes out. I can't give you the actual output of my code since it's not with this example here. I don't know how exactly it is being ordered. I need the keys to be assigned as ng-model and the values to be displayed. So I don't think I can just extract the values, sort them and display them. Any help would be appreciated! :) In the link the order is correct. I'm not sure why but I think it's because I am defining the fruitList in the javascript file, not being passed as a message from Java file.

http://jsfiddle.net/Lvc0u55v/7921//


Solution

  • Apparently, it's because I'm using a JSON object, not JSON array. This way I can prevent the ordering to be changed.