我在angularJS中使用分页来显示来自API调用的搜索内容。问题是我在所有页面上获得相同的数据集。 以下是我的尝试方式。
在控制器中
$rootScope.currentPage = 0;
$scope.pageSize = 5;
$scope.numberOfPages = function () {
return Math.ceil($scope.GetsearchResults.length / $scope.pageSize);
}
GetsearchResults是Json数组:它是当时的响应
在Html Im中使用ng-repeat for li tag
<li class="redirection clearfix" ng-repeat="result in GetsearchResults | startFrom:currentPage * pageSize | limitTo:pageSize" ng-click="GetEditFormData(result.fromUrl,result.Markets);ShowEditRedirect($event);"> //some contents </li>
<div class="pagination" ng-if="resultCount > 10"><button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage
-1">Previous</button> {{currentPage+1}}/{{numberOfPages()}}<button ng-disabled="currentPage >= GetsearchResults.length/pageSize - 1" ng-click="currentPage=currentPage+1"> Next </button></div>
我的控制器中有startFrom Filter,如下所示
app.filter('startFrom', function () {
return function (input, start) {
if (!input || !input.length) { return; }
start = +start ; //parse to int
return input.slice(start);
}
});
过滤器中的启动变量总是得到值0.我认为currentPage在ng-repeat中没有增加。我不明白为什么?
我对此进行了评论 - &gt; :http://jsfiddle.net/2ZzZB/56/
答案 0 :(得分:1)
由于您在分页菜单中使用了ng-if
,因此您需要访问$parent
范围,就像这个简单的 demo fiddle 一样。 ng-if
为其子项创建了一个独立的范围。
<div ng-controller="MyCtrl">
<ul>
<li class="redirection clearfix" ng-repeat="result in GetsearchResults | startFrom:currentPage * pageSize | limitTo:pageSize">
{{ result }}
</li>
</ul>
<div class="pagination" ng-if="GetsearchResults.length > pageSize">
<button ng-disabled="currentPage == 0"
ng-click="$parent.currentPage=$parent.currentPage-1">
Previous
</button>
{{currentPage+1}}/{{GetsearchResults.length / pageSize | ceil }}
<button ng-disabled="currentPage >= GetsearchResults.length/pageSize - 1"
ng-click="$parent.currentPage=currentPage+1">
Next
</button>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.currentPage = 0;
$scope.pageSize = 5;
$scope.GetsearchResults = [{
id: 1
}, {
id: 5
}, {
id: 11
}, {
id: 31
}, {
id: 12
}, {
id: 3
}, {
id: 33
}, {
id: 34
}, {
id: 52
}, {
id: 103
}, {
id: 33
}
];
});
/**
* Start from filter
*/
myApp.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
myApp.filter('ceil', function() {
return function(input) {
return Math.ceil(input);
};
});
答案 1 :(得分:1)
在div中使用 ng-show 代替 ng-if 。
<div class="pagination" **ng-show**="resultCount > 10">
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage
-1">Previous</button> {{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= GetsearchResults.length/pageSize - 1" ng-click="currentPage=currentPage+1"> Next </button></div>