Search code examples
javascriptangularjsng-options

How to populate selectbox in angularJS?


This my json data how to set a selected option of a dropdown list control using angular JS

$scope.alltoys=[
       {
         "dId": "570b886545034f0001718247",
         "dName": "Toys",
         "dSubName": "Comics",
         "users": [
           {
                "name": "Superman",
                "id": "570b9e3a45034f000171827b"
           },
           {
                "name": "Batman",
                "id": "570ba00045034f000171828a"
           }]
       },
       {
        "dId": "5767c68c52faff0001fb8555",
        "dName": "Toys",
        "dSubName": "General",
        "users": [
           {
                "name": "Jack",
                "id": "570b9e3a45034f000171827b"
           },
           {
                "name": "Sparrow",
                "id": "570ba00045034f000171828a"
           }]
        }
]

How to populate this select box using angular js

I want to populate like this

Toys-Comics
    Batman
    Superman
Toys-General
    Jack
    Sparrow

In here Toys-Comics & Toys-General are only title of that selected content I want to sort users array when populate.

<div class="controls">
    <select class="form-control" ng-model="toy"
        ng-options="eachtoy as eachtoy.dName+' - '+eachtoy.dSubName group by eachtoy for eachtoy in alltoys">
        <option value="">---------------Select---------------</option>
    </select>
</div>

I tried this but its not working.


Solution

  • Couple of changes. First, make sure $scope.alltoys is a collection (array), like this:

    $scope.alltoys = [{
      "dId": "570b886545034f0001718247",
      "dName": "Toys",
      "dSubName": "Comics",
      "users": [{
        "name": "Superman",
        "id": "570b9e3a45034f000171827b"
      }, {
        "name": "Batman",
        "id": "570ba00045034f000171828a"
      }]
    }, {
      "dId": "5767c68c52faff0001fb8555",
      "dName": "Toys",
      "dSubName": "General",
      "users": [{
        "name": "Jack",
        "id": "570b9e3a45034f000171827b"
      }, {
        "name": "Sparrow",
        "id": "570ba00045034f000171828a"
      }]
    }];
    

    Then change your html to handle groups with optgroup, like this:

    <select class="form-control" ng-model="toy">
      <option value="">---------------Select---------------</option>
      <optgroup ng-repeat="eachtoy in alltoys | orderBy: 'dName + dSubName" label="{{eachtoy.dName+' - '+eachtoy.dSubName}}">
        <option ng-repeat="user in eachtoy.users | orderBy: 'name'">{{user.name}}</option>
      </optgroup>
    </select>
    

    Here's a working plunk