如何将http调用传递给getData函数?

时间:2016-06-01 15:02:00

标签: javascript angularjs pagination offset ngtable

我的活动日志页面中的记录限制为最多100个。 我正试图在页面上找到一种分页的方法。设置为每页50条记录。 有没有办法将$http.get(‘/api/activity’)调用传递给getData函数并在http调用上添加偏移量,以便每次页码更改时偏移数都会改变?

angular.module('myApp').controller('ActivityLogController', function($scope, $log, $rootScope, $http, $state, $interval, $stateParams, NgTableParams, $filter) {
  return $scope.initActivity = function() {
    return $http.get('/api/activity').then(function(response) {
      $scope.activity = _.map(response.data, function(activity) {
        var ref, ref1;
        if (activity.User) {
          activity.name = ((ref = activity.User) != null ? ref.firstName : void 0) + " " + ((ref1 = activity.User) != null ? ref1.lastName : void 0);
        } else {
          activity.name = "Null User";
        }
        return activity;
      });
      $scope.activity = _.orderBy($scope.activity, ['createdAt'], ['desc']);
      return $scope.activityTable = new NgTableParams({
        sorting: {
          day: 'asc'
        },
        page: 1,
        count: 50
      }, {
        total: $scope.activity.length,
        counts: [],
        getData: function($defer, params) {
          var filteredData, orderedData, slicedData;
          filteredData = params.filter() ? $filter('filter')($scope.activity, params.filter()) : $scope.activity;
          orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : filteredData;
          slicedData = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
          return $defer.resolve(slicedData);
        }
      });
    });
  };
});

1 个答案:

答案 0 :(得分:1)

您可以在getData函数中使用promises并返回要显示的数组。

var Api = $resource("/data");
this.tableParams = new NgTableParams({}, {
  getData: function(params) {
    // ajax request to api
    return Api.get(params.url()).$promise.then(function(data) {
      params.total(data.inlineCount); // recal. page nav controls
      return data.results;
    });
  }
});

您可以在Ng-Table

页面上看到此示例

Ng-Table with a promise