如何用angular获取json对象的名称

时间:2016-05-11 09:55:34

标签: javascript jquery angularjs json

我试图从我的数据集中获取json对象(在这种情况下为bdev0bdev1)的名称。

到目前为止,我已经尝试过ng-options而没有成功。我想在下面的代码中实现的只是检索json对象的名称。到目前为止,我尝试的所有例子都不适用于我的案例。

jsfiddle

代码:

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.data = [{
        "Block_Devices": {
            "bdev0": {
                "Backend_Device_Path": "/dev/ram1",
                "Capacity": "16777216",
                "Bytes_Written": 1577,
                "timestamp": "4365093970",
                "IO_Operations": 17757,
                "Guest_Device_Name": "vdb",
                "Bytes_Read": 17793,
                "Guest_IP_Address": "192.168.26.88"
            },
            "bdev1": {
                "Backend_Device_Path": "/dev/ram2",
                "Capacity": "16777216",
                "Bytes_Written": 1975,
                "timestamp": "9365093970",
                "IO_Operations": 21380,
                "Guest_Device_Name": "vdb",
                "Bytes_Read": 20424,
                "Guest_IP_Address": "192.168.26.100"
            }
        },
        "Number of Devices": 2
    }]

}

HTML

<div ng-controller="MyCtrl">
  <select name="Block_Devices" ng-model="selectedDevice"  ng-options="value.Block_Devices for value in data">
  <option value="">Please Select Device</option>
    </select>
</div>
Selected Device = {{selectedDevice}}

2 个答案:

答案 0 :(得分:1)

您可以使用ng-repeat="(key, value) in array"语法。

<div ng-repeat="(key, value) in data[0].Block_Devices">
{{key}}
</div>

{{key}}将是Block_Devices的财产 请参阅示例jsfiddle

答案 1 :(得分:1)

正如Bon在我之前所说,你可以按照jsfiddle

进行操作
  <select name="Block_Devices" ng-model="selectedDevice.Bytes_Written" ng-options="key for (key, value) in data[0].Block_Devices">
    <option value="">Please Select Device</option>
  </select>