ng-repeat show only last element

All we need is an easy explanation of the problem, so here it is.

I am developing inbox for messages with AngularJs, and I came across one issue: I want to show only last element within ng-repeat. I did some research, and found out that the code below should work.

<div class="inbox" ng-repeat="recipient in messages">
  <ul>
    <div> 
      <span> {{recipient.$id}} <br> </span>
      <li class="inboxItem">
        <span ng-repeat="messages in recipient"> {{messages.sender}} {{messages.message}} <br></span>
      </li>
    </div>
  </ul>
</div>

However, it does not. Can you guys tell me what am I doing wrong? I thought that array.length-1 should limit ng-repeat to show only the last object in an array.

Thanks!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

use angularjs $last in ng-repeat. here is the doc

<div ng-repeat="n in data track by $index">
   <span ng-show="$last">{{n}}</span>
</div>

<span ng-show="$last">{{n}}</span> when its last repeat $last will be true otherwise its false so you can use ng-show or ng-if with $last.

here is a sample demo


UPDATE
I think no need of ng-repeat there since you need to show the last element of the array (this is same as @Michael P. Bazos’s answer), to do that:

$scope.data = [42, 42, 43, 43, 50];

print the last value as : {{ data[data.length-1] }}

here is the demo

but if you really need to do with ng-repeat do as this

[data[data.length-1]] create an array only with last element.

<div ng-repeat="n in [data[data.length-1]] track by $index">
    <span>{{n}}</span>
</div>

demo

Method 2

You could use limitTo filter with -1

Example :

<div ng-repeat="friend in friends | limitTo: -1">
    {{friend.name}}
</div>

See fiddle

But if you are showing only one element, maybe you want to get rid of the ng-repeat… :

<div>
    {{friends[friends.length - 1].name}}
</div>

Method 3

Something like this should work.

<div ng-repeat="something in vm.somethings">
  <span ng-show="$last">{{ something.value }}</span>
</div>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply