Search code examples
javascriptangularjsselectng-optionsangularjs-ng-options

Bind enum values to ng-options angular js


The response JSON from a http GET method is as shown below

 [
    {
        "1": "Open"
    },
    {
        "2": "Expired"
    }
]

How to bind this data in a select drop down box in angular js. I tried with this option:

<select class="form-control" ng-model="selected" ng-options="item for item in data"> 
<option value="">----Select----</option> 
</select>

But I'm getting [object,object] in the drop down list.


Solution

  • You could transform the json data into the format expected by ng-options simply using Array.reduce, along the lines of

    $scope.options = data.reduce(function(memo, obj) {
        return angular.extend(memo, obj);
    }, {});
    
    <select ng-model="selected" ng-options="key as val for (key, val) in options"></select>
    

    Full example here http://plnkr.co/edit/PV4BYrz0KBkIFPWVzVaT?p=preview