I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

Dropdown value is not binding with associative array

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>

Upvotes: 0

Views: 254

Answers (1)

Hadi
Hadi

Reputation: 17299

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>

Upvotes: 2

Related Questions