Summer Developer Summer Developer - 1 month ago 12
AngularJS Question

Angular Ng-Repeat First Of Type

I have some json like this that I'm pulling from a

$http
and assigning to the scope to iterate over with
ng-repeat


JSON:

[{"id":19,"Name":"Apple Pie","Type":"Pies"},
{"id":20,"Name":"Old Fashioned Pumpkin Pie","Type":"Pies"},
{"id":21,"Name":"White Rolls","Type":"Rolls"},
{"id":27,"Name":"Honey Sandwich","Type":"Sandwich"}]


What I want is in the list made by the
ng-repeat
, something like this markup

-Pies

--Apple Pie

--Old Fashioned Pumpkin Pie

-Rolls

--White Rolls

-Sandwich

--Honey Sandwich

So instead of this

<div class="form-group" ng-repeat="bread in breads">
<label for="exampleInputPassword1">@{{bread.Name}}</label>
</div>


Something like this:

<div class="form-group" ng-repeat="bread in breads">
<label for="thing">@{{bread.Type}}</label><!--But only if first of type-->
<label for="exampleInputPassword1">@{{bread.Name}}</label>
</div>


Basically the only thing I can come up with is this:

-Pies

--Apple Pie

-Pies

--Old Fashioned Pumpkin Pie

When I don't want "Pies" to be repeated twice just because there are two pies, I want to separate out by type. The
$first
property only applies to the entire collection I believe, so it is of no help here. Is there anything I can do short of reforming the JSON?

Answer

You can do this,

<div ng-controller="MyCtrl">
    <ul ng-repeat="(key, value) in breads | groupBy: 'Type'">
        <b>{{ key }}</b>
      <li ng-repeat="breado in value">
          <i>{{ breado.Name }} </i>
      </li>
    </ul>
</div>

DEMO