Anwin Anwin - 2 months ago 12
AngularJS Question

how to use ng-options and ng-select with json

Can somebody explain how to use ng-options when I have below json:

{
"key1":
{
"name":"test1",
"code":"horizontal",
"fields":[
{
"type":"email"
},
{
"type":"text"
}
]
},
"key2":
{
"name":"test2",
"code":"vertical",
"fields":[
{
"type":"emai"
},
{
"type":"text"
}
]
}
}


and then i try to create select like this

<select name="cert" id="cert" ng-options="item as item[paramm] for item in listcert track by $index"></select>


where "paramm" = $key in json.

I want to see something like this

<select>
<option value="horizontal" label='horizontal'>test1</option>
<option value="vertical" label='vertical'>test2</option>
</select>


I have no idea how it works. Please help...

Answer

Is this what you were looking for? The trick here is that your data is not in an array format

var data = {
    "key1": {
            "name":"test1",
            "code":"horizontal",
            "fields":
                [{
                    "type":"email",
                },{
                    "type":"text",
                }]
        }, "key2": {
            "name":"test2",
            "code":"vertical",
            "fields":
                [{
                    "type":"emai",
                },{
                    "type":"text",
                }]
        }
}

angular.module("app", [])
        .controller("MainController", MainController);

function MainController() {
  var vm = this;
  vm.selected = {};
  vm.dataArray = [];
  
  angular.forEach(data, function(value, key) {
    vm.dataArray.push(value);
  }, data);
  
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MainController as main">
  <select ng-options="value as value.code for value in main.dataArray track by value.name" ng-model="selected"></select>

<h3>Selected value:</h3>
<pre>{{selected | json}}</pre>
</div>

Comments