M-S M-S - 2 months ago 17
AngularJS Question

How to show / hide a multiple list of items in angular

I have multiple ul lists, with ng-repeat. Initially i need to display 4items and then i have to display remaining items.

Requirement:


  1. If the 1st ul has only 1 item, then the items from the 2nd ul 3 items should show and then click on show more remaining items of 2nd ul should show.

  2. If the 1st ul has greater than 4 items, then on click of show more remaining items including 2nd ul should be shown.



Currently it is showing both the ul with 4 items each on load on click of show more it is showing the last list item in both the ul blocks.

this is what I tried:

HTML:

<div ng-controller="myCtrl">
<b>With more than 4 items:</b>
<ul>
<li ng-repeat="item in manyItems | limitTo:limit2">{{item}}</li>
</ul>
<ul>
<li ng-repeat="item in manyItems | limitTo:limit2">{{item}}</li>
</ul>
<button ng-click="setLimit2(4)"
ng-disabled="(limit2===4)||(manyItems.length<=4)">
Show few
</button>
<button ng-click="setLimit2(0)"
ng-disabled="manyItems.length<=limit2">
Show all
</button>
</div>


JS:

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
/* Config 2 */
$scope.manyItems = ['item 1', 'item 2', 'item 3','item 4', 'item 5'];
$scope.limit2 = 4;
$scope.setLimit2 = function (lim) {
$scope.limit2 = (lim <= 0) ? $scope.manyItems.length : lim;
};
});


Fiddle Demo

Answer

You can try the following code:

HTML

<div ng-controller="myCtrl">

   <b>With more than 4 items:</b>

   <ul>
      <li ng-repeat="item in manyItems | limitTo:limit1"> {{item}} </li>
   </ul>

   <ul>
      <li ng-repeat="item in manyItems2 | limitTo:limit2">{{item}}</li>
</ul>

<button ng-click="setLimit2()"> Show few </button>
<button ng-click="showAll()"> Show all </button>

Angular

var app = angular.module('myApp', []);

app.controller('myCtrl', function ($scope) {
    /* Config 2 */
    $scope.manyItems = ['item 31', 'item 41', 'item 51'];
    $scope.manyItems2 = ['item 12', 'item 222', 'item 32','item 42', 'item 52'];

    $scope.firstLimit = $scope.manyItems.length > 4 ? true: false;

    $scope.limit1 = 0;
    $scope.limit2 = 0;

    $scope.setLimit2 = function (  ) {
       ( $scope.firstLimit ) ? $scope.limit1 = 4 : $scope.limit1 = $scope.manyItems.length, $scope.limit2 = 4 - $scope.manyItems.length ;
    };

    $scope.setLimit2();

    $scope.showAll = function() {
       ( $scope.firstLimit ) ? $scope.limit1 = $scope.manyItems.length :  $scope.limit2 = $scope.manyItems2.length; 
    }
});  

jsFiddle Demo

Comments