Paymon Wang-Lotfi
Paymon Wang-Lotfi

Reputation: 555

Pagination in AngularJS

I'm using Bootstrap's Pagination directive to add pagination to a table.

What is so strange about this is that when I manually add to $scope.transactions (see commented out code in the controller), the pagination works perfectly fine. But when I try to populate $scope.transactions via an AJAX call, the table shows nothing. The AJAX call returns the following:

[{"date":"2017-01-06","amount":123,"action":"Deposit","id":1},{"date":"2017-01-06","amount":200,"action":"Deposit","id":2},{"date":"2017-01-06","amount":400,"action":"Deposit","id":3}]

View:

    <tr ng-repeat="transaction in f ">

    <td>{{transaction.id}}</td>
    <td>$ {{transaction.amount}}</td>
    <td>{{transaction.action}}</td>
    <td>{{transaction.date}}</td>
    </tr>
    </table>
    <pagination 
          ng-model="currentPage"
          total-items="transactions.length"
          max-size="maxSize"  
          boundary-links="true">
        </pagination>  

Controller:

 var mmyApp = angular.module('myApp',['ui.bootstrap']).controller('TasksController',  TasksController);
     function TasksController($scope, $http) {

     $scope.f = []
      ,$scope.currentPage = 1
      ,$scope.numPerPage = 3
      ,$scope.maxSize = 5;
     $scope.transactions = [];
    $scope.history = "";

    $http.get('transactions').then(function (response) {

         $scope.transactions = response.data;
     }, function (error) {
         throw error;
     });

     //if i use this commented out code instead of the AJAX call, the pagination works fine
     /*$scope.makeTransactions = function() {
            $scope.transactions = [];
            for (i=1;i<=1000;i++) {
              $scope.transactions.push({"id":i});
            }
          };
          $scope.makeTransactions();
          */
     $scope.$watch('currentPage + numPerPage', function() {
            var begin = (($scope.currentPage - 1) * $scope.numPerPage)
            , end = begin + $scope.numPerPage;

            $scope.f = $scope.transactions.slice(begin, end);
          });


 }

Upvotes: 1

Views: 241

Answers (1)

Alex Polkhovsky
Alex Polkhovsky

Reputation: 3360

You forgot to populate $scope.fafter populating $scope.transactions in your ajax call. In your ng-repeat you're cycling through items that should be stored in $scope.f but it's empty.

Upvotes: 1

Related Questions