我正在使用Bootstrap 4和 AngularJS v1.6.6 制作一个小的 Contacts应用程序。
应用程序仅显示 Users JSON。由于JSON返回了大量用户,因此该应用程序还具有分页功能。
作为应用程序控制器的一部分,分页效果很好,但是由于我试图将其转变为服务,因此它不再起作用。
查看应用程序的功能版本,并在控制器内进行分页 HERE。
应用程序控制器:
// Create an Angular module named "contactsApp"
var app = angular.module("contactsApp", []);
// Create controller for the "contactsApp" module
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
var url = "https://randomuser.me/api/?&results=100&inc=name,location,email,cell,picture";
$scope.contactList = [];
$scope.search = "";
$scope.filterList = function() {
var oldList = $scope.contactList || [];
$scope.contactList = $filter('filter')($scope.contacts, $scope.search);
if (oldList.length != $scope.contactList.length) {
$scope.pageNum = 1;
$scope.startAt = 0;
};
$scope.itemsCount = $scope.contactList.length;
$scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
};
$http.get(url)
.then(function(data) {
// contacts arary
$scope.contacts = data.data.results;
$scope.filterList();
// Pagination Service
$scope.paginateContacts = function(){
$scope.pagination = paginationService.paginateContacts();
}
});
}]);
服务:
app.factory('paginationService', function(){
return {
paginateContacts: function(){
// Paginate
$scope.pageNum = 1;
$scope.perPage = 24;
$scope.startAt = 0;
$scope.filterList();
$scope.currentPage = function(index) {
$scope.pageNum = index + 1;
$scope.startAt = index * $scope.perPage;
};
$scope.prevPage = function() {
if ($scope.pageNum > 1) {
$scope.pageNum = $scope.pageNum - 1;
$scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
}
};
$scope.nextPage = function() {
if ($scope.pageNum < $scope.pageMax) {
$scope.pageNum = $scope.pageNum + 1;
$scope.startAt = ($scope.pageNum - 1) * $scope.perPage;
}
};
}
}
});
在视图中:
<div ng-if="pageMax > 1">
<ul class="pagination pagination-sm justify-content-center">
<li class="page-item"><a href="#" ng-click="prevPage()"><i class="fa fa-chevron-left"></i></a></li>
<li ng-repeat="n in [].constructor(pageMax) track by $index" ng-class="{true: 'active'}[$index == pageNum - 1]">
<a href="#" ng-click="currentPage($index)">{{$index+1}}</a>
</li>
<li><a href="#" ng-click="nextPage()"><i class="fa fa-chevron-right"></i></a></li>
</ul>
</div>
服务文件包含在项目中(我认为是正确的),app.js
文件之后:
<script src="js/app.js"></script>
<script src="js/paginationService.js"></script>
我不是AngularJS的高级用户,所以我不知道:缺少什么?
答案 0 :(得分:1)
似乎需要在控制器之前定义服务,否则将无法正确注入。
因此您可以将paginationService
移至app.js
:
var app = angular.module("contactsApp", []);
app.factory('paginationService', function(){
//...
});
app.controller("contactsCtrl", ["$scope", "$http", "$filter", "paginationService", function($scope, $http, $filter) {
//...
});
或者将控制器移到paginationServices.js
文件之后的单独文件中。
看看this plunker。尝试修改第6行-删除字符5,即将星号和斜线分开的空格,以关闭多行注释。