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

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

问题描述

我有一个项目清单...

$scope.Users =[{用户名: ''}];

在我看来,假设我的 $scope:Users

中只有 4 个项目,我想像这样列出它们

用户名 1、用户名 2、用户名 3 和用户名 4<span data-ng-repeat="user in Users">{{user.Username}}</span>{{$last ?'' : ', '}}

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

我的问题是如何在最后一项之前添加 and 关键字,这样它就会像:

用户名 1、用户名 2、用户名 3 和用户名 4

代替:

用户名1、用户名2、用户名3、用户名4

解决方案

$last 是真值.

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

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

还要确保您在 ng-repeat 元素中使用 $last 表达式,而不是在它之外

请检查下面的工作小提琴

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

I have a list of items ...

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

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.

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

Username1, Username2, Username3 and Username4

instead of:

Username1, Username2, Username3, Username4

解决方案

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

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,在最后一项之前用“and"分隔的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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