0

I have an associative array like below which I want to bind with my dropdown:

{
        "Item1": [
          {
            "title": "Item1",
            "choices": [
              "Egg",
              "burger",
            ]
          }
        ],
        "Item2": [
          {
            "title": "Item2",
            "choices": [
              "Pizza",
              "Rice",
            ]
          }
        ]
     }

I am trying to bind dropdown based on this associative array, but the problem is it is displaying as object object.

I want to show title in dropdown for each of the item like below:

Item1
Item2

I have tried to take reference from below SO question but it didn't work out:

key-value pairs in ng-options

Angularjs ng-options with an array of key-pair

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {
    $scope.item=
    {
        "Item1": [
          {
            "title": "Item1",
            "choices": [
              "Egg",
              "burger",
            ]
          }
        ],
        "Item2": [
          {
            "title": "Item2",
            "choices": [
              "Pizza",
              "Rice",
            ]
          }
        ]
     }

 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <ul ng-app="myApp" ng-controller="MyController">
     <select ng-model="myItem.title" ng-options="key as value for (key , value) in item">
           <option value="">Select Items</option>
     </select>
</ul>
halfer
  • 19,824
  • 17
  • 99
  • 186
I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216
  • do your item details (the Object with title, choices) need to be wrapped in array? would be easier to parse without that array wrapper. – jdubjdub Aug 28 '17 at 18:24
  • @jdubjdub actually I am having various types of items like french,Italian,chineses in which each of this items will have some choices I.e is I have this items as associative array – I Love Stackoverflow Aug 28 '17 at 18:39

1 Answers1

2

It should be like to this:

   ng-options="value as key for (key , value) in item">

var app = angular.module("myApp", []);
app.controller("MyController", function ($scope) {

    $scope.item=
    {
        "Item1": [
          {
            "title": "Item1",
            "choices": [
              "Egg",
              "burger",
            ]
          }
        ],
        "Item2": [
          {
            "title": "Item2",
            "choices": [
              "Pizza",
              "Rice",
            ]
          }
        ]
     }

 });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <ul ng-app="myApp" ng-controller="MyController">
     <select ng-model="myItem.title" ng-options="value as key for (key , value) in item">
           <option value="">Select Items</option>
     </select>
     
     {{myItem.title}}
</ul>
Hadi J
  • 16,989
  • 4
  • 36
  • 62