如何使用AngularJS ng-repeat打破值?

时间:2013-07-16 18:29:40

标签: javascript angularjs

我希望我能解释一下我的目标。

我正在从API中检索项目列表。为简单起见,我们假设这是返回的JSON:

[ { id: 1, name: "Project 1", pm: "msmith"}, 
  {id: 2, name: "Project 2", pm: "msmith"},
  {id: 3, name: "Project 3", pm: "msmith"},
  {id: 4, name: "Project 4", pm: "sjones"},
  {id: 5, name: "Project 5", pm: "sjones"} ]

项目列表将按照下午按名称排序。我希望这些项目显示在这样的页面上:

msmith (3 projects)
    Project 1
    Project 2
    Project 3

sjones (2 projects)
    Project 4
    Project 5

如何在AngularJs中执行此操作?

1 个答案:

答案 0 :(得分:2)

因此,您需要一些功能来获取不同pms的列表

<div ng-repeat="pm in distinctPms">
  {{pm}}
  <ul>
      <li ng-repeat="name in items | filter:{pm: pm}">
          {{name.name}}
      </li>
  </ul>
</div> 

function SimpleController($scope) {

  function distinctPm() {
    var unique= [];
    for (var i = 0; i < $scope.items.length; i++) {
        if (unique.indexOf($scope.items[i].pm) == -1) {
            unique.push($scope.items[i].pm)
        }
    }
    return unique;
  }

  $scope.items = [ 
    {id: 1, name: "Project 1", pm: "msmith"}, 
    {id: 2, name: "Project 2", pm: "msmith"},
    {id: 3, name: "Project 3", pm: "msmith"},
    {id: 4, name: "Project 4", pm: "sjones"},
    {id: 5, name: "Project 5", pm: "sjones"}
  ];

  $scope.distinctPms = distinctPm();

}