Thomas Grauer
Thomas Grauer

Reputation: 140

How to return the last item in ng-repeat to the controller

I would like to run a string function, to remove the comma on the last span element.

<p class="genres">
    <span class="plabel">Genres</span>: 
    <span class="genre_name" ng-repeat="genres in movie.genres"
          ng-class="{'last': $last}">{{genres.name}}, 
    </span>
</p>

Upvotes: 2

Views: 1060

Answers (2)

Leonardo Chaia
Leonardo Chaia

Reputation: 2835

You can use the $last boolean on a ternary operator inside interpolation:

{{genres.name}} {{$last ? '' : ','}}

$last (boolean): true if the repeated element is last in the iterator.

If you want to perform more string manipulation, maybe you could also use an Angular filter: (Untested)

angular.module('testFilter', [])
.filter('addComma', function() {
  return function(input, shouldAddComma) {
    if (shouldAddComma)
       return input + ",";
    else 
       return input;
  };
});

And then in your HTML:

{{genres.name | addComma: $last}}

This is just an example of how you can use an Angular filter to modify the string and also receive a parameter.

Upvotes: 5

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Just add ng-if like this

<span class="genre_name" ng-repeat="genres in movie.genres"
          ng-class="{'last': $last}">{{genres.name}}<label ng-if="!$last">,</label>
    </span>

Upvotes: 4

Related Questions