Search code examples
angularjs-ng-repeatangularjs-limitto

ng-repeat with limitTo feature with start index


Let us say I have [1,2,3,4,5,6,7] array, I need to split into it so that I always have 3 objects, i.e. [1,2,3], [4,5,6] , [5,6,7] on clicking next in the page. How to achieve this using start index and limitTo feature of angularjs?


Solution

  • Checking against the length of the array in your ng-click handler would be the way I'd go about this.

    Something like the following:

    $scope.items = [1, 2, 3, 4, 5, 6, 7];
    
    $scope.startFrom = 0;
    
    $scope.nextPage = function () {
        if ($scope.startFrom + 3 > $scope.items.length - 3) {
            $scope.startFrom = $scope.items.length - 3;
        }
        else {
            $scope.startFrom += 3;
        }
    };
    

    And then:

    ng-repeat="item in items | limitTo: 3: startFrom"
    

    If you have any problems with startFrom you may need to check your version of Angular. See this post for more info.