AngularJS与laravel模型分页 - 分页栏未正确显示

时间:2017-05-15 11:23:37

标签: php mysql angularjs laravel-5

以下是我使用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值的问题,但我无法修复它是分页栏的截图

enter image description here

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

1 个答案:

答案 0 :(得分:2)

有点想这样。我对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));
}