简体   繁体   中英

How do I break on values using AngularJS ng-repeat?

I hope I can explain what I'm looking to do.

I am retrieving a list of projects from an API. To make things simple, let's say this is the JSON returned:

[ { 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"} ]

The list of projects will be sorted by pm then by name. I want the items to display on a page like this:

msmith (3 projects)
    Project 1
    Project 2
    Project 3

sjones (2 projects)
    Project 4
    Project 5

How can I do this in AngularJs?

So you'll need some functionality to get a list of the distinct 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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM