Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 843
forgottofly Avatar asked Dec 24 '14 10:12

forgottofly


2 Answers

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

like image 91
mcfedr Avatar answered Nov 19 '22 00:11

mcfedr


you need a key,value in ng-repeat syntax as you have unknown or different keys

And you have to keep track of two repeats first for array and then for keys inside the objects

<select class="form-control" ng-model="selected" > 
<option value="">----Select----</option> 
   <optgroup ng-repeat="v in values">

     <option ng-repeat='(key,value) in v' value="{{key}}">{{value}}</option>
   </optgroup>  
</select>

Demo

value in option will be "open" or "expired" you can change it to keys "0" or "1" if you replace value={{value}} with value="{{key}}"

app = angular.module('test',[]);
app.controller('testctrl',function($scope){
$scope.values =[{"1": "Open" },{"2": "Expired" }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="testctrl" ng-app="test">
<span ng-if="selectedModel">{{selectedModel}}</span>
<select class="form-control"  ng-model="selectedModel"> 
<option>----Select----</option> 
   <optgroup ng-repeat="v in values">
     
     <option ng-repeat='(key,value) in v' value="{{value}}">{{value}}</option>
   </optgroup>  
</select>
  </div>
like image 3
A.B Avatar answered Nov 19 '22 00:11

A.B