Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-repeat, comma separated with 'and' before the last item

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 
like image 756
David Dury Avatar asked Nov 14 '14 09:11

David Dury


2 Answers

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

like image 73
Hrishi Avatar answered Sep 18 '22 11:09

Hrishi


This could be one of the solutions

<span data-ng-repeat="user in Users">{{user.Username}}<font ng-show="!$last">,</font></span> 
like image 36
amarmishra Avatar answered Sep 17 '22 11:09

amarmishra