AngularJS ng-repeat,在最后一项之前用逗号“和"分隔 [英] AngularJS ng-repeat, comma separated with 'and' before the last item

查看:48
本文介绍了AngularJS ng-repeat,在最后一项之前用逗号“和"分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个物品清单...

I have a list of items ...

$scope.Users =[{
    UserName: ''
}];

在我看来,我想像这样列出它们,前提是我的$scope:Users

In my view I want to list them like this assuming I have only 4 items in my $scope:Users

Username1, Username2, Username3 and Username4

<span data-ng-repeat="user in Users">{{user.Username}}</span>{{$last ? '' : ', '}}

上面的表达式基本上会在每个项目后添加逗号,并且可以正常工作.

The above expression will basically add comma after each item and works fine.

我的问题是我如何在最后一项之前添加and关键字,使其类似于:

My problem is how do I add an and keyword before the last item so it will be like:

Username1, Username2, Username3 and Username4

代替:

Username1, Username2, Username3, Username4

推荐答案

$ last是真实值..因此它包含true或false,并且不包含最后一个元素索引..

$last is the truthy value.. so it holds either true or false and it doesn't hold the last element index..

我想下面的表达式应该可以解决您的问题

I guess below expression should solve your problem

<p><span ng-repeat="user in Users">
            {{user.Username}} {{$last ? '' : ($index==Users.length-2) ? ' and ' : ', '}}
  </span></p>

还要确保您在ng-repeat元素之内而不是在其外部具有$ last表达式

Also make sure that you have the expression with $last within ng-repeat element and not outside of it

请检查下面的工作小提琴

Please check the below working fiddle

http://jsfiddle.net/hrishi1183/Sek8F/2/

这篇关于AngularJS ng-repeat,在最后一项之前用逗号“和"分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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