Search code examples
javascriptjsonangularjsdrop-down-menung-options

Displaying JSON data in drop-down in AngularJS


my document.json file contains data like

[
    {"name" :"B"},
    {"name" :"A"},
    {"name" :"D"},
    {"name" :"E"}
]

when i try to display the json data in drop-down list, the last element E only displayed in drop down .my html file like

<select ng-model="selectedTestAccount" ng-options="c as c.name for c in testAccounts"></select>

and my script file like

sampleApp.controller('DemoCtrl', function ($scope, $http) {
  $scope.selectedTestAccount = null;
  $scope.testAccounts = [];

  $http.get('document.json').success(function (data) {
    $scope.testAccounts = data;
  });
});

How can i display this document.json data in drop-down list with default selected as first element in AngularJS. Any guidelines please


Solution

  • Your JSON isn't quite right. You need to have braces around each item, like this:

    [ 
      { "name" :"B" }, 
      { "name" :"A" }, 
      { "name" :"D" }, 
      { "name" :"E" } 
    ]
    

    You can select the first item in the dropdown by default like this:

    $scope.selectedTestAccount = $scope.testAccounts[0];
    

    Demo