Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular filter with pagination

I am using a filter on an array of items in a ng-repeat like this:

<input type="text" ng-model="filterText">

<li ng-repeat="item in displayItems | filter : {item_name: filterText}>

This works fine and filters the items perfectly.The problem arises because I am using displayItems with a uib-pagination element. The pagination uses totalItems instead of displayItems.

<uib-pagination class="pagination-sm pagination"
    total-items="totalItems.length" ng-model="page" ng-change="changeItems()">
</uib-pagination>

Obviously I need to somehow apply the filter on the total-items, then create the displayItems, and put the filteredItems in the uib-pagination.

Ie. When the person types, in the controller the filter is applied to the totalItems, and I create the filteredItems needed for the pagination. I also then create the displayItems from the filteredItems. How do I go about putting this into the controller and not in the HTML for the ng-repeat?

I'm not sure how to do this. Any thoughts? All help much appreciated....

I've included a plunker to show it (not) working in all its glory.... https://plnkr.co/edit/EYX6zO1795sD9TYq2J8U?p=preview

like image 569
Tom O'Brien Avatar asked Jul 17 '16 14:07

Tom O'Brien


2 Answers

Try,

HTML,

<li ng-repeat="item in filterData = (totalItems | filter : {itemName: filterText}) | limitTo:3:3*(page-1)">

and

<uib-pagination class="pagination-sm pagination" total-items="filterData.length" ng-model="page"
        ng-change="pageChanged()" previous-text="&lsaquo;" next-text="&rsaquo;" items-per-page=3></uib-pagination>

JavaScript,

$scope.pageChanged = function() {
  //var startPos = ($scope.page - 1) * 3;
  //$scope.displayItems = $scope.totalItems.slice(startPos, startPos + 3);
};

https://plnkr.co/edit/m3jXsxsCGfqKCJYHsw0u?p=preview

like image 180
user1111 Avatar answered Oct 15 '22 06:10

user1111


You can access the filtered array by using as alias in ng-repeat expression

<li ng-repeat="item in displayItems | filter : {item_name: filterText} as filteredArray">

Then use that alias for total-items in pagination

<uib-pagination class="pagination-sm pagination"
    total-items="filteredArray.length" ng-model="page" ng-change="changeItems()">
</uib-pagination>
like image 36
charlietfl Avatar answered Oct 15 '22 06:10

charlietfl