tothefux tothefux - 3 months ago 9
AngularJS Question

ng-repeat show subtitle for first type of item

I have a list of objects that have all the same fields except for its type. I would like to show a subtitle in the ng-repeat right before this type of item is rendered. Right now I have x ng-repeats for x types of items and its becoming unmanageable. The blocks are all the same except for the subtitle. Assume that the scope array doesn't have types scattered, they're subdivided with its type. For example, when rendered I would like to show this.

Rendered

Cats
cat 1
cat 2
cat 3

Dogs
dog 1
dog 2
dog 3

Lizards
lizard 1
lizard 2
lizard 3


Model

$scope.animals = [
{ name: "cat 1", type: "cat" },
{ name: "cat 2", type: "cat" },
{ name: "cat 3", type: "cat" },
{ name: "dog 1", type: "dog" },
{ name: "dog 2", type: "dog" },
{ name: "dog 3", type: "dog" },
{ name: "lizard 1", type: "lizard" },
{ name: "lizard 2", type: "lizard" },
{ name: "lizard 3", type: "lizard" }
];


View

<div ng-repeat="animal in animals">
<!-- if first animal type appearing show subtitle -->
{{animal.name}}
</div>


I do not want to structure my data this way which I'm doing now and rendering redundant ng-repeats.

Model

$scope.cats = [
...
];
$scope.dogs = [
...
];
$scope.lizards = [
...
];


View

<h2>Cats</h2>
<div ng-repeat="cat in cats">
{{cat.name}}
</div>

<h2>Dogs</h2>
<div ng-repeat="dog in dogs">
<h2>Dogs</h2>
{{dog.name}}
</div>

<h2>Lizards</h2>
<div ng-repeat="lizard in lizards">
{{lizard.name}}
</div>


Thanks in advance!

osi osi
Answer

You need to check if the type is different from the previous type. You can get this item using $index - 1

   <div ng-repeat="animal in animals">
      <h1 ng-if="animal.type != animals[$index - 1]">
        {{ animal.type }}
      </h1>
      {{animal.name}}
    </div>
Comments