ng-repeat을 사용한 목록 페이지 번호 지정
목록에 페이지를 추가하려고 합니다.Angular를 따라갔다.JS 튜토리얼은 스마트폰에 대한 튜토리얼로, 저는 특정 개수의 객체만 표시하려고 합니다.다음은 저의 html 파일입니다.
<div class='container-fluid'>
<div class='row-fluid'>
<div class='span2'>
Search: <input ng-model='searchBar'>
Sort by:
<select ng-model='orderProp'>
<option value='name'>Alphabetical</option>
<option value='age'>Newest</option>
</select>
You selected the phones to be ordered by: {{orderProp}}
</div>
<div class='span10'>
<select ng-model='limit'>
<option value='5'>Show 5 per page</option>
<option value='10'>Show 10 per page</option>
<option value='15'>Show 15 per page</option>
<option value='20'>Show 20 per page</option>
</select>
<ul class='phones'>
<li class='thumbnail' ng-repeat='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit'>
<a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
<a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
표시되는 항목의 수를 제한하기 위해 값이 포함된 선택 태그를 추가했습니다.지금 원하는 것은 페이지 수를 추가하여 다음 5, 10 등을 표시하는 것입니다.
다음과 같은 기능을 하는 컨트롤러가 있습니다.
function PhoneListCtrl($scope, Phone){
$scope.phones = Phone.query();
$scope.orderProp = 'age';
$scope.limit = 5;
}
그리고 저는 json 파일에서 데이터를 불러오기 위한 모듈을 가지고 있습니다.
angular.module('phonecatServices', ['ngResource']).
factory('Phone', function($resource){
return $resource('phones/:phoneId.json', {}, {
query: {method: 'GET', params:{phoneId:'phones'}, isArray:true}
});
});
데이터가 많지 않다면 브라우저에 모든 데이터를 저장하고 특정 시간에 보이는 데이터를 필터링하는 것만으로 페이지 매김을 확실히 할 수 있습니다.
다음은 angular.js Github Wiki의 피들목록에 있는 간단한 페이지 번호 매기기 예시입니다.이것은 도움이 될 것입니다.
var app=angular.module('myApp', []);
function MyCtrl($scope) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.numberOfPages=function(){
return Math.ceil($scope.data.length/$scope.pageSize);
}
for (var i=0; i<45; i++) {
$scope.data.push("Item "+i);
}
}
//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in data | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button>
{{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= data.length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
승인된 답변을 복사했지만 HTML에 Bootstrap 클래스를 추가했습니다.
var app=angular.module('myApp', []);
function MyCtrl($scope) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.numberOfPages=function(){
return Math.ceil($scope.data.length/$scope.pageSize);
}
for (var i=0; i<45; i++) {
$scope.data.push("Item "+i);
}
}
//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
<html xmlns:ng="http://angularjs.org" ng-app lang="en">
<head>
<meta charset="utf-8">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" rel="stylesheet">
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
</head>
<body>
<script type="text/javascript">
var sortingOrder = 'name';
</script>
<div ng-controller="ctrlRead">
<div class="input-append">
<input type="text" ng-model="query" ng-change="search()" class="input-large search-query" placeholder="Search">
<span class="add-on"><i class="icon-search"></i></span>
</div>
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th class="id">Id <a ng-click="sort_by('id')"><i class="icon-sort"></i></a></th>
<th class="name">Name <a ng-click="sort_by('name')"><i class="icon-sort"></i></a></th>
<th class="description">Description <a ng-click="sort_by('description')"><i class="icon-sort"></i></a></th>
<th class="field3">Field 3 <a ng-click="sort_by('field3')"><i class="icon-sort"></i></a></th>
<th class="field4">Field 4 <a ng-click="sort_by('field4')"><i class="icon-sort"></i></a></th>
<th class="field5">Field 5 <a ng-click="sort_by('field5')"><i class="icon-sort"></i></a></th>
</tr>
</thead>
<tfoot>
<td colspan="6">
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length)"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</td>
</tfoot>
<tbody>
<tr ng-repeat="item in pagedItems[currentPage] | orderBy:sortingOrder:reverse">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.field3}}</td>
<td>{{item.field4}}</td>
<td>{{item.field5}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
메모리 내 페이지를 매우 간단하게 표시할 수 있는 모듈을 만들었습니다.
간단히 치환하여 페이지 번호를 매길 수 있습니다.ng-repeat와 함께dir-paginate페이지당 항목을 파이프 필터로 지정한 후 원하는 위치에 단일 지시 형식으로 컨트롤을 놓습니다.<dir-pagination-controls>
Tomarto가 질문한 원래의 예를 들어보자면 다음과 같다.
<ul class='phones'>
<li class='thumbnail' dir-paginate='phone in phones | filter:searchBar | orderBy:orderProp | limitTo:limit | itemsPerPage: limit'>
<a href='#/phones/{{phone.id}}' class='thumb'><img ng-src='{{phone.imageUrl}}'></a>
<a href='#/phones/{{phone.id}}'>{{phone.name}}</a>
<p>{{phone.snippet}}</p>
</li>
</ul>
<dir-pagination-controls></dir-pagination-controls>
컨트롤러에 특별한 페이지 번호 코드가 필요 없습니다.이 모든 것은 모듈에 의해 내부적으로 처리됩니다.
데모: http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview
출처: GitHub의 dirPagination.
이 스레드가 오래된 것은 알지만, 조금 최신 정보를 유지하기 위해 응답합니다.
Angular 1.4 이상의 경우 limit를 직접 사용할 수 있습니다.limit매개 변수도 사용할 수 있습니다.begin파라미터를 지정합니다.
사용방법:{{ limitTo_expression | limitTo : limit : begin}}
따라서 페이지 번호 부여와 같은 작업을 수행하기 위해 서드파티 라이브러리를 사용할 필요가 없습니다.나는 그것을 설명하기 위해 바이올린을 만들었다.
다음 디렉티브를 확인해 주세요.https://github.com/samu/angular-table
정렬과 페이지 매김을 많이 자동화하여 원하는 대로 테이블/리스트를 자유롭게 커스터마이즈할 수 있습니다.
페이지 번호 + 각도 필터링이 있는 데모 코드입니다.JS:
https://codepen.io/lamjaguar/pen/yOrVym
JS:
var app=angular.module('myApp', []);
// alternate - https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
// alternate - http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/paginating-through-client-side-data.html
app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
// needed for the pagination calc
// https://docs.angularjs.org/api/ng/filter/filter
return $filter('filter')($scope.data, $scope.q)
/*
// manual filter
// if u used this, remove the filter from html, remove above line and replace data with getData()
var arr = [];
if($scope.q == '') {
arr = $scope.data;
} else {
for(var ea in $scope.data) {
if($scope.data[ea].indexOf($scope.q) > -1) {
arr.push( $scope.data[ea] );
}
}
}
return arr;
*/
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
for (var i=0; i<65; i++) {
$scope.data.push("Item "+i);
}
// A watch to bring us back to the
// first pagination after each
// filtering
$scope.$watch('q', function(newValue,oldValue){ if(oldValue!=newValue){
$scope.currentPage = 0;
}
},true);
}]);
//We already have a limitTo filter built-in to angular,
//let's make a startFrom filter
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
HTML:
<div ng-app="myApp" ng-controller="MyCtrl">
<input ng-model="q" id="search" class="form-control" placeholder="Filter text">
<select ng-model="pageSize" id="pageSize" class="form-control">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<ul>
<li ng-repeat="item in data | filter:q | startFrom:currentPage*pageSize | limitTo:pageSize">
{{item}}
</li>
</ul>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button> {{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= getData().length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
언급URL : https://stackoverflow.com/questions/11581209/pagination-on-a-list-using-ng-repeat
'programing' 카테고리의 다른 글
| JsonRequestBehavior를 AllowGet으로 설정할 때 어떤 '중요한 정보'가 공개될 수 있습니까? (0) | 2023.04.04 |
|---|---|
| Oracle의 기본 날짜 형식은 YYY-MM-DD입니다. 이유는 무엇입니까? (0) | 2023.04.04 |
| 오류 응답 Spring Boot에서 "message" 필드가 비어 있습니다. (0) | 2023.04.04 |
| 각 JS 브레이크 (0) | 2023.04.04 |
| Objective-C 개체를 JSON으로 직렬화 및 직렬화 해제 (0) | 2023.04.04 |