AngularJs:输出嵌套JSON的最佳方式

时间:2015-08-07 08:30:08

标签: angularjs

我的角度应用程序中有以下格式的数据:

"lists":
    {
        "list1":
            [
                { "id": "1001", "type": "Regular" },
                { "id": "1002", "type": "Chocolate" },
                { "id": "1003", "type": "Blueberry" },
                { "id": "1004", "type": "Devil's Food" }
            ],
        "list2":
            [
                { "id": "1001", "type": "Regular" },
                { "id": "1002", "type": "Chocolate" },
                { "id": "1003", "type": "Blueberry" },
                { "id": "1004", "type": "Devil's Food" }
            ]
    }

我通常使用ng-repeat来循环数据和输出,但因为这些数据是嵌套的,所以我不确定输出它的最佳方法是什么。我想要创建以下标记结构:

<div>
  <h2>list1</h2>
  <ul>
     <li data-id="1001">Regular<li>
      <!-- more list items here -->
  </ul>
</div>

2 个答案:

答案 0 :(得分:1)

$scope.data = {
 "lists":
    {
        "list1":
            [
                { "id": "1001", "type": "Regular" },
                { "id": "1002", "type": "Chocolate" },
                { "id": "1003", "type": "Blueberry" },
                { "id": "1004", "type": "Devil's Food" }
            ],
        "list2":
            [
                { "id": "1001", "type": "Regular" },
                { "id": "1002", "type": "Chocolate" },
                { "id": "1003", "type": "Blueberry" },
                { "id": "1004", "type": "Devil's Food" }
            ]
    }
}

IN html

<div ng-repeat ="(key,lists) in data.lists">
  <h2>{{key}}</h2>
    <ul>
         <li  ng-repeat="val in lists track by val.id" data-id="{{val.id}}">{{val.type}}</li>
    </ul>
</div>

PlUNKER

答案 1 :(得分:1)

请查看工作示例:DEMO

HTML

<div ng-repeat="(key, value) in data.lists">
  {{key}}
  <div ng-repeat="subList in value">
      {{subList.id}} {{subList.type}}
  </div>
</div>

控制器

$scope.data = {
      "lists":
      {
          "list1":
           [
                 { "id": "1001", "type": "Regular" },
                 { "id": "1002", "type": "Chocolate" },
                 { "id": "1003", "type": "Blueberry" },
                 { "id": "1004", "type": "Devil's Food" }
           ],
           "list2":
            [
                 { "id": "1001", "type": "Regular" },
                 { "id": "1002", "type": "Chocolate" },
                 { "id": "1003", "type": "Blueberry" },
                 { "id": "1004", "type": "Devil's Food" }
            ]
      }
} 
相关问题