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

David Dury picture David Dury · Nov 14, 2014 · Viewed 43.3k times · Source

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

Answer

Hrishi picture Hrishi · Nov 14, 2014

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