Aimad MAJDOU Aimad MAJDOU - 3 months ago 77x
AngularJS Question

Implementing a "Load More" button to load more elements when its clicked

I want my li elements to be hidden and when my state loads I want to display only the first two elements and when I click on a button o show the next two elements and so on.

This is how it should work :

In my angular application I display my li elements as following :

<ul id="myList">
<li ng-repeat="offre in offres |orderBy:'-dateCreation'|filter:{etat:'true'}">
<div class="box">
<!-- HTML Code -->

I have li elements set to
and a javascript code that shows the first two elements as following :


size_li = $("#myList li").size();
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= x+2;
$('#myList li:lt('+x+')').show();


The problem is when my state loads all the li elements are shown and not only the first two elements, as you can see in the fiddle I attached it works but it doesn't work when I use it with ng-repeat.

How can I solve this?


As you are using Angular, you should try to avoid directly manipulating the DOM in this way where possible. Instead you should take advantage of Angular directives to control how elements are displayed, in this case ng-show.

You are already storing the list in the $scope.offres. You just need to keep track of how many items to show and only show it if the $index available in ng-repeat is lower than that value:

angular.module('myapp', []).controller('ctrl1', function($scope) {

  // set up the list with dummy data
  $scope.offres = [];
  for (var i = 0; i < 11; i++) {
    $scope.offres.push(i + 1);

  // set initial index
  // we will use this variable to control the display - see ng-show="" in HTML
  $scope.loadIndex = 2;

  // function to increase visible items
  $scope.showMore = function() {
    // don't increment if at the end of the list
    if ($scope.loadIndex < $scope.offres.length) {
      $scope.loadIndex += 2;

  // function to decrease visible items
  $scope.showLess = function() {
    // don't decrement if at the start of the list
    if ($scope.loadIndex > 2) {
      $scope.loadIndex -= 2;
#loadMore {
  color: green;
  cursor: pointer;
#loadMore:hover {
  color: black;
#showLess {
  color: red;
  cursor: pointer;
<script src=""></script>

<div ng-app="myapp" ng-controller="ctrl1">
  <ul id="myList">
    <li ng-repeat="offre in offres" ng-show="$index < loadIndex">{{offre}}</li>
  <div id="loadMore" ng-click="showMore()">Load more</div>
  <div id="showLess" ng-click="showLess()">Show less</div>

As you can see, it is then trivial to implement showing less items, as you are just changing a number in your controller.