L457
L457

Reputation: 1032

Check if next item exists inside an ng-repeat item

I'm using ng-repeat with a limitTo filter and a button to raise the limit when clicked. Is there any way to check if the next item in the ng-repeat iteration exists/count how many more items there are so that i can hide the 'load more' button/show how many more items there are.

below is sort of an example of what I am trying to do:

 <div ng-repeat="comment in collection.data | limitTo:commentLimit">               
            {{comment.text}}
   <div ng-show="filteredItems[$index + 1]" ng-click="increaseLimit()">load more (3 more replies)</div>
</div>

Upvotes: 1

Views: 1245

Answers (2)

Travis
Travis

Reputation: 5061

Ideally, I think what you want to do is set an increment value in your scope, and add a new function called nextIncrementAmount which will help you display the number of new replies the button will add when clicked.

$scope.commentLimit = 3;
$scope.incrementStep = 3;

//use this function to increase the filter limit
$scope.increaseLimit = function() {
    var newLimit = $scope.commentLimit + $scope.incrementStep;

    $scope.commentLimit = (newLimit < $scope.collection.data.length) ? newLimit : $scope.collection.data.length;

}

//use this function to show the number of replies the increment button will increment by.
$scope.nextIncrementAmount = function() {
    var newLimit = $scope.commentLimit + $scope.incrementStep;

    return (newLimit < $scope.collection.data.length) ? $scope.incrementStep : $scope.collection.data.length - $scope.commentLimit;
}

Then in your view you'll want to do something like this:

<div ng-repeat="comment in collection.data | limitTo:commentLimit">               
    {{comment.text}}
</div>
<div ng-if="collection.data.length != commentLimit" 
     ng-click="increaseLimit()">
     load more (<ng-pluralize count="nextIncrementAmount()"
                              when="{
                                 '1': '{} more reply',
                                 'other': '{} more replies',
                              }"> </ng-pluralize>)
</div>

Upvotes: 0

Eylen
Eylen

Reputation: 2677

You can do something similar to this codepen: http://codepen.io/anon/pen/waxOZL

<div ng-repeat="comment in collection.data | limitTo:commentLimit">               
    {{comment.text}}
</div>
<div ng-show="collection.data.length > commentLimit" ng-click="increaseLimit()">load more (3 more replies)</div>

Also, you should put the load more link outside the ng-repeat to show it only once.

Upvotes: 1

Related Questions