将JSON对象中的项目推送到角度js中的下拉列表

时间:2016-02-10 13:16:02

标签: javascript jquery angularjs json

我有一个json文件

var myJson = {
   "Number of Devices":2,
   "Block Devices":{
      "bdev0":{
         "Backend_Device_Path":"/dev/ram1",
         "Capacity":"16777216",
         "Bytes_Written":9848,
         "timestamp":"4365093970",
         "IO_Operations":87204,
         "Guest_Device_Name":"vdb",
         "Bytes_Read":107619,
         "Guest_IP_Address":"192.168.26.88"
      },
      "bdev1":{
         "Backend_Device_Path":"/dev/ram2",
         "Capacity":"16777216",
         "Bytes_Written":10062,
         "timestamp":"9365093970",
         "IO_Operations":93789,
         "Guest_Device_Name":"vdb",
         "Bytes_Read":116524,
         "Guest_IP_Address":"192.168.26.100"
      }
   }
}

我想在下拉菜单中推送块设备的名称。在查看一些示例之后,名称是bdev0和bdev1我尝试了以下代码,但我只是在下拉列表中返回[Object object]

视图

<select ng-model="selectedDevice" ng-options="item as devices['Block Devices'] for item in selectdevice">
    <option value="">Select Device</option>
   </select>

和控制器

    .controller('timeSeriesCtrl', function($scope, $timeout, $http) {

    $scope.selectedDevice = null;
    $scope.selectdevice = [];
    $scope.bytesRead = [];
    $scope.bytesWritten = [];
    $scope.IoOps = [];
    $scope.currentTime = [];
    var path = 'http://orbit5.ds.cs.umu.se:8888/vrio/debug/blk'


function getData(){
  $http.get(path)
  .success(function(data){
    $scope.devices = data
    angular.forEach($scope.devices['Block Devices'], function(value, key){

           $scope.selectdevice = key;
})


  })
}

getData();





  });

2 个答案:

答案 0 :(得分:2)

删除forEach的所有代码,并使用(key,value)的{​​{1}}语法

ng-options

在html中:

function getData(){
  $http.get(path)
  .success(function(data){
    $scope.devices = data
    //angular.forEach($scope.devices['Block Devices'], function(value, key){
       //$scope.selectdevice = key;
    //   value.key = key;
    //})
  });

小提琴:https://jsfiddle.net/ncapito/4mqFJ/6/

答案 1 :(得分:1)

object.toString() = [object object]. Object.prototype.toString()

您可以使用(key, content)语法显示密钥。

<select ng-model="selectedItem">
      <option ng-repeat="(key, content) in myjson['Block Devices']" value="{{item}}">{{key}}</option>
</select>