【问题标题】:AngularJS pagination with laravel model - pagination bar is not displayed properlyAngularJS分页与laravel模型 - 分页栏未正确显示
【发布时间】:2017-05-15 11:23:36
【问题描述】:

这是我用 angular bootstrap pagination 构建分页的 AngularJS 代码:

$scope.employees = [],
$scope.currentPage = 0,
$scope.numPerPage = 2,
$scope.totalItems = '',
$scope.maxSize = 2;

$scope.getEmployee = function (offset) {
    $http.get('/employee/'+offset).then(function (response) {
        $scope.employees = response.data.data;
        $scope.totalItems=  response.data.totalRows;
        console.log($scope.totalItems);
    });
};

$scope.getEmployee(0);

$scope.getPage = function () {
    $scope.getEmployee($scope.currentPage === 1 ? 0 : $scope.currentPage);
};

尝试每页列出 2 名员工(现在我在 mysql 查询中有 6 行)

Laravel 控制器

public function getTotalEmployees($offset)
{
    $result =  Company::limit(2)->offset($offset)->get();
    return response()->json(array('data'=>$result,'totalRows'=>Company::count()));
}

查询将给出正确的输出,但分页栏没有正确显示。

HTML

<ul>
    <li ng-repeat="emp in employees">{{emp.name}}</li>
</ul>
<pagination
    ng-model="currentPage"
    total-items="20"
    max-size="maxSize"
    boundary-links="true"
    ng-change="getPage()">
</pagination>

我认为这是totalItems 值的问题,但我无法修复这里是分页栏的屏幕截图

我无法选择禁用的下一个和上一个按钮

【问题讨论】:

  • 您从数据库 (Company::limit(2)) 中选择 2 个项目,然后在基于每页 2 个项目的分页列表中对其进行解析。那么,您为什么期望页面多于一页?没有“下一页”时,下一个被禁用是正常的,不是吗?
  • 所以我需要获取所有行??但是当表超过 20000 行时它会崩溃??
  • 20000 个项目在您只输出一个属性(如“title”)作为文本时不是问题。它确实取决于您输出的数据量以及“行”HTML 结构的复杂性。
  • 数据太多了,所以认为这是个坏主意
  • 所以,比起只加载需要在当前页面上显示的数据应该没问题。但是您需要另一个 API 端点来获取项目的“总数”以创建一个不错的分页。

标签: php mysql angularjs laravel-5


【解决方案1】:

这样想。我对 laravel 不是很熟悉,但它应该可以为你做一些小的修改。我在 laravel 中添加了另一个控制器操作,它返回您的项目总数。此 API 端点在 this.$onInit 上调用,这是自 AngularJS 1.5 以来可用的方法。它会在控制器初始化时被调用。这是一个带有分页示例的简单 fiddle demo

AngularJS 控制器

$scope.employees = [],
$scope.currentPage = 0,
$scope.numPerPage = 2,
$scope.totalItems = 0,
$scope.maxSize = 2;

this.$onInit = function () {
    $scope.getEmployee();
    $http.get('/employee/getTotalCount').then(function (response) {
        $scope.totalItems = response.data.count;
    });
};

$scope.getEmployee = function () {
    $http.get('/employee/getItems/'+ ($scope.currentPage * $scope.numPerPage) +'/' + $scope.numPerPage).then(function (response) {
        $scope.employees = response.data.data;
    });
};


$scope.getPage = function () {
    $scope.getEmployee();
};

Laravel 控制器

public function getTotalCount()
{
    $companies = Company::all();
    return response()->json('count' => $companies->count());
}

public function getItems($offset, $limit)
{
    $result = Company::limit($limit)->offset($offset)->get();
    return response()->json(array('data'=>$result));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多