ng-repeat只显示最后一个元素 [英] ng-repeat show only last element

查看:269
本文介绍了ng-repeat只显示最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发用于AngularJs消息的收件箱,但遇到一个问题:我只想显示ng-repeat中的最后一个元素.我做了一些研究,发现下面的代码应该可以工作.

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>

但是,事实并非如此.你们能告诉我我在做什么错吗?我认为array.length-1应该将ng-repeat限制为仅显示数组中的最后一个对象.

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.

谢谢!

推荐答案

ng-repeat中使用angularjs $last.这是文档

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>当其最后一次重复$last时将是true,否则为false,因此您可以将ng-showng-if$last一起使用.

<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.

这是一个示例演示

更新 我认为这里不需要ng-repeat,因为您需要显示数组的最后一个元素(与@Michael P. Bazos的答案相同),才能做到这一点:

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] }}

这是演示

但是如果您确实需要使用ng-repeat,请这样做

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

[data[data.length-1]]仅使用最后一个元素创建一个数组.

[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>

演示

这篇关于ng-repeat只显示最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆