Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-repeat show only last element

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!

like image 633
uksz Avatar asked Mar 21 '15 13:03

uksz


People also ask

How do I get an index in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

What can I use instead of NG-repeat?

You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

How does ng-repeat work?

Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

Does ng-repeat create a new scope?

Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.


2 Answers

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

like image 104
Kalhan.Toress Avatar answered Oct 23 '22 20:10

Kalhan.Toress


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>
like image 44
Michael P. Bazos Avatar answered Oct 23 '22 21:10

Michael P. Bazos