AngularJS Group By对象属性

时间:2016-04-04 16:05:36

标签: javascript angularjs

我有这个对象:

  $scope.items = [{ 
    "category": { "code": "10", "description": "Movies" },
        "item": {"code": "421", "description": "Noriko's Dinner Table" }
                  },{ 
    "category": { "code": "10", "description": "Movies" },
        "item": {"code": "511", "description": "Avatar" }
                  },{ 
    "category": { "code": "45", "description": "Books" },
        "item": {"code": "93", "description": "Divergent" }
                  },{ 
    "category": { "code": "45", "description": "Books" },
        "item": {"code": "72", "description": "Sense and Sensibility" }
                  },{ 
    "category": { "code": "33", "description": "TV Shows" },
        "item": {"code": "11", "description": "The Walking Dead" }
                  },{ 
    "category": { "code": "33", "description": "TV Shows" },
        "item": {"code": "60", "description": "The Bates Motel" }
                  }];

我正在尝试对它们进行分组,以便列表可以整齐地组织和查看。像这样:

enter image description here

但正如您所看到的,类别说明出现在每个项目上。我该怎么办?

  <ul>
    <li ng-repeat="item in items track by $id(item)"><div>{{item.category.description}}</div>{{item.item.description}}</li>
  </ul>

现场演示:http://plnkr.co/edit/mjek9xPo3ihBTiwW6U0V?p=preview

1 个答案:

答案 0 :(得分:3)

你想做这样的事情:

<ul ng-repeat="(key, value) in items | groupBy: 'category.description'">
 {{ key }}
   <li ng-repeat="item in value">
     {{ item.item.description }} 
   </li>
</ul>

利用groupByfilter内置的角度。