显示带有ng重复的JSON

Displaying JSON with ng repeat

本文关键字:JSON ng 显示      更新时间:2023-09-26

我有一个格式为的JSON数据

[
    {
        "_1": {
            "id": 4,            
            "cost": 45.0,
            "measure": 4,
            "NoOfUnits": 677,            
            "hours": null
        },
        "_2": {
            "id": 1,
            "name": "Truck",
            "description": "Test"        
        }
    },
    {
        "_1": {
            "id": 1,
             "cost": 1120.0,
            "measure": 1,
            "NoOfUnits": 500,
             "hours": null
        },
        "_2": {
            "id": 7,
            "name": "PC300",
            "description": null           
        }
    },
]

我无法显示存储在$scope变量中的数据,比如

$scope.result

这是我的ng重复功能

<div ng-repeat="data in result">{{data.name}}{{data.description}}</div>

您的$scope.result包含2 objects,其中一个对象中有一组类似_1,_2object properties,然后这些properties又是类似的对象

"_1": {
    "id": 4,            
    "cost": 45.0,
    "measure": 4,
    "NoOfUnits": 677,            
    "hours": null
}

,则您有需要打印的properties

<ul>
  <li ng-repeat="x in result">        // repeats objects
       <ul ng-repeat="obj in x">      // repeat object properties '_1',"_2" , these are again objects
           {{obj.name}}{{obj.description}}
       <ul>
  </li>
</ul>

使用您的数据结构。。。您不能从第一个ng重复直接访问名称和描述。

即使你嵌套了ng重复,你也不能保证有名字和描述。您需要在第一次ng重复后展平对象,然后才能访问所有属性。假设_1,_2对象属性是相关的。

需要两个循环---

<div ng-repeat="data in result">
   <div ng-repeat="obj in data">
       {{obj.cost}}{{obj.name}}
    </div>
</div>

演示:http://jsfiddle.net/HB7LU/8254/