I am working on a small application that displays a "users" JSON in an HTML5 table. It uses Bootstrap 3 and AngularJS. I want to paginate this table.
I do not have an array to loop through, with ng-repeat. I have the number of pages.
var root = 'https://jsonplaceholder.typicode.com';
// Create an Angular module named "usersApp"
var app = angular.module("usersApp", []);
// Create controller for the "usersApp" module
app.controller("usersCtrl", ["$scope", "$http", "$filter", function($scope, $http, $filter) {
var url = root + "/users";
$scope.userList = [];
$scope.search = "";
$scope.filterList = function() {
$scope.userList = $filter('filter')($scope.users, $scope.search);
$scope.itemsCount = $scope.userList.length;
$scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
};
$http.get(url)
.then(function(data) {
// Users arary
$scope.users = data.data;
$scope.filterList();
// Order by function
$scope.orderByMe = function(criteria) {
$scope.myOrderBy = criteria;
}
// Paginate
$scope.pageNum = 1;
$scope.perPage = 3;
$scope.startAt = 0;
$scope.filterList();
$scope.currentPage = function() {
$scope.startAt = $scope.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;
}
};
});
}]);
.table-container {
margin: 10px 0 0 0 !important;
}
.table-responsive {
margin: 0 !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div data-ng-app="usersApp">
<div class="container" data-ng-controller="usersCtrl">
<div class="panel panel-default table-container">
<div class="panel-heading">Users</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group search-box">
<input type="text" class="form-control" id="search"
placeholder="Search User" data-ng-model="search"
ng-change="filterList()">
</div>
</div>
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-striped table-bordered" id="dataTable">
<thead>
<tr>
<th>#</th>
<th ng-click="orderByMe('name')">Full name</th>
<th ng-click="orderByMe('email')">Email</th>
<th ng-click="orderByMe('city')">City</th>
<th>Street</th>
<th>Suite</th>
<th>Zipcode</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in userList|orderBy:myOrderBy| limitTo : perPage : startAt">
<td>{{$index + startAt + 1}}</td>
<td>{{user.name}}</td>
<td>{{user.email | lowercase}}</td>
<td>{{user.address.city}}</td>
<td>{{user.address.street}}</td>
<td>{{user.address.suite}}</td>
<td>{{user.address.zipcode}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="text-center" ng-if="pageMax > 1">
<ul class="pagination pagination-sm">
<li><i class="fa fa-chevron-left"></i></li>
<li ng-repeat="n in [].constructor(pageMax) track by $index">
{{$index+1}}
</li>
<li><i class="fa fa-chevron-right"></i></li>
</ul>
</div>
</div>
</div>
Whenever I click the Next and Previous page pagination items (the chevrons), the script works right, but when I click the numbered pagination items, the $scope.startAt variable does not update and the table row numbers are NaN.
What am I doing wrong?
Invoke the currentPage function with $index as an argument:
<ul class="pagination pagination-sm">
<li><i class="fa fa-chevron-left"></i></li>
<li ng-repeat="n in [].constructor(pageMax) track by $index">
̶<̶a̶ ̶h̶r̶e̶f̶=̶"̶#̶"̶ ̶n̶g̶-̶c̶l̶i̶c̶k̶=̶"̶c̶u̶r̶r̶e̶n̶t̶P̶a̶g̶e̶(̶)̶"̶>̶{̶{̶$̶i̶n̶d̶e̶x̶+̶1̶}̶}̶<̶/̶a̶>̶
{{$index+1}}
</li>
<li><i class="fa fa-chevron-right"></i></li>
</ul>
BEFORE
$scope.currentPage = function() {
$scope.startAt = $scope.index * $scope.perPage;
};
After
$scope.currentPage = function(index) {
$scope.pageNum = index+1;
$scope.startAt = index * $scope.perPage;
};
How would you update the pagination with the search filter?
$scope.filterList = function() {
var oldList = $scope.userList || [];
$scope.userList = $filter('filter')($scope.users, $scope.search);
if (oldList.length != $scope.userList.length) {
$scope.pageNum = 1;
$scope.startAt = 0;
};
$scope.itemsCount = $scope.userList.length;
$scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
};
The DEMO
angular.module("usersApp", [])
.controller("usersCtrl", function($scope, $http, $filter) {
var root = '//jsonplaceholder.typicode.com';
var url = root + "/users";
$scope.userList = [];
$scope.search = "";
$scope.filterList = function() {
var oldList = $scope.userList || [];
$scope.userList = $filter('filter')($scope.users, $scope.search);
if (oldList.length != $scope.userList.length) {
$scope.pageNum = 1;
$scope.startAt = 0;
};
$scope.itemsCount = $scope.userList.length;
$scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage);
};
// Order by function
$scope.orderByMe = function(criteria) {
$scope.myOrderBy = criteria;
};
$http.get(url)
.then(function(response) {
$scope.users = response.data;
$scope.filterList();
// Paginate
$scope.pageNum = 1;
$scope.perPage = 3;
$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;
}
};
});
.table-container {
margin: 10px 0 0 0 !important;
}
.table-responsive {
margin: 0 !important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div data-ng-app="usersApp">
<div class="container" data-ng-controller="usersCtrl">
<div class="panel panel-default table-container">
<div class="panel-heading">Users</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group search-box">
<input type="text" class="form-control" id="search" placeholder="Search User" data-ng-model="search" ng-change="filterList()">
</div>
</div>
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-striped table-bordered" id="dataTable">
<thead>
<tr>
<th>#</th>
<th ng-click="orderByMe('name')">Full name</th>
<th ng-click="orderByMe('email')">Email</th>
<th ng-click="orderByMe('city')">City</th>
<th>Street</th>
<th>Suite</th>
<th>Zipcode</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in userList|orderBy:myOrderBy| limitTo : perPage : startAt">
<td>{{$index + startAt + 1}}</td>
<td>{{user.name}}</td>
<td>{{user.email | lowercase}}</td>
<td>{{user.address.city}}</td>
<td>{{user.address.street}}</td>
<td>{{user.address.suite}}</td>
<td>{{user.address.zipcode}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="text-center" ng-if="pageMax > 1">
<ul class="pagination pagination-sm">
<li><i class="fa fa-chevron-left"></i></li>
<li ng-repeat="n in [].constructor(pageMax) track by $index">{{$index+1}}
</li>
<li><i class="fa fa-chevron-right"></i></li>
</ul>
</div>
</div>
</div>
Related
Can anybody help me how to fix this flicker effect when view is loading here is my code.
app.config(function($stateProvider,$urlRouterProvider,$routeProvider, $locationProvider,blockUIConfig) {
$urlRouterProvider.otherwise("/#");
$stateProvider
.state('dash', {
url: "/dash",
templateUrl: 'views/br_manager/pc_dashboard.html',
controller:'dashCtrl'
})
.state('pass', {
url: "/pass",
templateUrl: 'views/br_manager/change_password.html',
controller:'passwordCtrl'
})
.state('classroom', {
abstract:true,
url: "/classroom",
template: '<div ui-view style="height:100%"></div>',
controller:'classroomManagementCtrl'
})
.state('classroom.list', {
url: "",
templateUrl: 'views/br_manager/CR.html'
})
$locationProvider.html5Mode(true);
blockUIConfig.message = "Processing ...";
});
following is the code for controller and factory sevrvice
branchManager.factory('classroomFactory',function($resource,appConfig,$window){
var factory = {};
var fetch_classroom_url = appConfig.getMainAPI();
var authCode = $window.localStorage.getItem("authCode");
factory.fetchStandardList = function(selectedYear) {
return $resource(fetch_classroom_url+'/classroom/year/'+ selectedYear, {}, {
fetch : {
method : 'get',
isArray : false,
headers : { 'Authorization' : authCode },
interceptor : {
response : function(data) {
return data;
}
}
}
});
};
factory.fetchSectionList = function(currentStandard, selectedYear) {
return $resource(fetch_classroom_url+'/classroom/standard/'+ currentStandard +'/section/year/'
+ selectedYear, {}, {
fetch : {
method : 'get',
isArray : false,
headers : { 'Authorization' : authCode },
interceptor : {
response : function(data) {
return data;
}
}
}
});
};
return factory;
});
branchManager.controller('classroomManagementCtrl', function($scope,classroomFactory,appConfig,$state,$modal) {
var initials = {
syllabus:"",section:"",standard:"",year:"",classRoomId:"",maxcount:"",maxCount:""
};
$scope.year_list = ["2015-16","2016-17","2017-18","2018-19"];
$scope.fetchYearList = function(){
$scope.selectedYear = $scope.year_list[0];
$scope.fetchStandardList($scope.selectedYear);
};
$scope.fetchStandardList = function(selectedYear){
var year = window.btoa(selectedYear);
classroomFactory.fetchStandardList(year).fetch({},function(response){
$scope.standard_list =[];
if(response.status == 200 || response.status == 201){
if(response.data.standards != undefined){
var _data = angular.fromJson(response.data.standards);
$scope.standard_list = _data;
console.log( $scope.standard_list);
if($scope.standard_list.length > 0){
$scope.currentStandard = $scope.standard_list[0];
$scope.fetchSectionList($scope.currentStandard,selectedYear);
}else{
$scope.standard_list = ["-Nil-"];
}
}
}
},function(response){
$scope.standard_list = [];
$scope.currentStandard = "-Nil-";
$scope.response_msg = "There is no Standards found for this year.";
$scope.fetchSectionList($scope.currentStandard,selectedYear);
console.log(response.status);
});
};
$scope.fetchSectionList = function(currentStandard,selectedYear){
$scope.response_msg = "";
var standart = window.btoa(currentStandard);
var year = window.btoa(selectedYear);
classroomFactory.fetchSectionList(standart,year).fetch({},function(response){
$scope.classroom_list =[];
console.log(response);
if(response.status == 200 || response.status == 201){
if(response.data.classRoomLists!=undefined){
var _data = angular.fromJson(response.data.classRoomLists);
$scope.classroom_list = _data;
console.log( $scope.classroom_list);
$scope.$parent.setBaseContentHeight($scope.classroom_list.length);
}
}
},function(response){
$scope.classroom_list = [];
$scope.response_msg = "There is no classrooms found for this standard.";
$scope.$parent.setBaseContentHeight(-1);
console.log(response.status);
});
};
$scope.init = function(){
$scope.fetchYearList();
console.log("Init called")
};
$scope.cancel = function () {
$scope.response_msg = "";
$scope.response_msg1 = "";
$state.go('^.list');
};
$scope.init();
});
and my view looks like
<div class="col-lg-8 base-content table-base" style="height:90%;">
<div class="container-fluid" style="height: 90%;padding:0">
<div class="container-fluid" style="height: 30px;padding:0">
<div class="col-lg-2 col-md-2 col-sm-4 col-xs-4" style="font-size: medium;padding: 0 0 10px 0px" >
<a ui-sref="^.add"><button type="button" ng-click="addClassroom()" class="btn btn-color btn-sm">Add ClassRooms</button></a>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="padding: 0 0 20px 20px">
<select class="input-sm form-control" ng-model="selectedYear"ng-change="fetchStandardList(selectedYear)" ng-options="year as year for year in year_list" style="line-height: 1.5">
<option value="" selected="selected">-Year-</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="padding: 0 0 20px 20px">
<select class="input-sm form-control" ng-model="currentStandard" ng-change="fetchSectionList(currentStandard,selectedYear)" ng-options="currentStandard as currentStandard for currentStandard in standard_list" style="line-height: 1.5">
<option value="" selected="selected">-Class-</option>
</select>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 text-success response_msg" style="padding-top: 10px;" ng-hide="response_msg == undefined || response_msg == ''" >{{response_msg}}</div>
</div>
<div class="container-fluid" style="height:auto;padding:0;" ng-if="classroom_list== undefined || classroom_list.length <= 10">
<table class="table table-striped">
<thead>
<tr>
<th width="10%">Classroom Id</th>
<th width="10%">Year</th>
<th width="10%">Standard</th>
<th width="10%">Section</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classroom_list">
<td width="10%">{{classroom.classRoomId}}</td>
<td width="10%">{{classroom.year}}</td>
<td width="10%">{{classroom.standard}}</td>
<td width="10%">{{classroom.section}}</td>
</tr>
</tbody>
</table>
<div ng-if="classroom_list.length == 0 || standard_list.length == 0" class="noData">No Classrooms Found</div>
<!-- <div ng-if="classroom_list == undefined " class="noData">Processing...</div>-->
</div>
<div class="container-fluid" style="padding:0" ng-if="classroom_list != undefined && classroom_list.length > 10">
<table class="table">
<thead>
<tr>
<tr>
<th width="10%">Classroom Id</th>
<th width="10%">Year</th>
<th width="10%">Standard</th>
<th width="10%">Section</th>
</tr>
</thead>
</table>
</div>
<div class="container-fluid slim-content" style="padding:0;" ng-if="classroom_list != undefined && classroom_list.length > 10" slim-scroll="{height:'88%',size:'3px',allowPageScroll :true,width:'100%'}">
<table class="table table-striped">
<tbody>
<tr ng-repeat="classroom in classroom_list">
<td width="10%">{{classroom.classRoomId}}</td>
<td width="10%">{{classroom.year}}</td>
<td width="10%">{{classroom.standard}}</td>
<td width="10%">{{classroom.section}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
any answers will be helpful thanks in advance.
I'm using angular 1.5.5 and angular-bootstrap 1.3.3 to paginate, sort and filter my data on a table via ng-repeat, but it is only sorting and filtering on the current page and not on all the pages.
app.js
var app = angular.module("sac.app", ['ngResource', 'ui.router', 'ui.bootstrap']);
app.config(function config($stateProvider, $urlRouterProvider) {
'use strict';
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html'
})
.state('patients', {
url: '/patients',
controller: 'PatientController',
templateUrl: 'views/patients.html'
});
app.controller('PatientController', ['$scope', 'patients', function ($scope, patients) {
patients.success(function (data) {
$scope.patients = data;
$scope.sortType = 'name';
$scope.sortReverse = true;
$scope.search = '';
$scope.currentPage = 1;
$scope.numPerPage = 2;
$scope.totalItems = $scope.patients.length;
$scope.maxSize = 5;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.patients.indexOf(value);
return (begin <= index && index < end);
};
})
}]);
app.factory('patients', ['$http', function ($http) {
return $http.get('api/patients')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
patients.html
<form>
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-search"></i></div>
<input type="text" class="form-control" placeholder="Ingrese el Nombre o Apellido del Paciente" ng-model="search" autofocus>
<div class="input-group-btn">
<a ui-sref="patient.create" class="btn btn-primary"><i class="fa fa-plus"></i> Nuevo Paciente</a>
</div>
</div>
</form>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>
<a href="" ng-click="sortType = 'name'; sortReverse = !sortReverse">
Nombre Completo
<span ng-show="sortType == 'name'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
<th>
<a href="" ng-click="sortType = 'identity'; sortReverse = !sortReverse">
Identificación
<span ng-show="sortType == 'identity'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
<th>
<a href="" ng-click="sortType = 'age'; sortReverse = !sortReverse">
Edad
<span ng-show="sortType == 'age'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
<th>
<a href="" ng-click="sortType = 'telephone'; sortReverse = !sortReverse">
Teléfono
<span ng-show="sortType == 'telephone'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
<th>
<a href="" ng-click="sortType = 'email'; sortReverse = !sortReverse">
Email
<span ng-show="sortType == 'email'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="patient in patients | orderBy:sortType:sortReverse | filter:paginate | filter:search">
<td>{{ patient.name }} {{ patient.last_name }}</td>
<td>{{ patient.identity }}</td>
<td>{{ patient.age }}</td>
<td>{{ patient.telephone }}</td>
<td>{{ patient.email }}</td>
</tr>
</tbody>
</table>
<uib-pagination first-text="Primera" last-text="Última" next-text=">" previous-text="<"
total-items="totalItems" items-per-page="numPerPage" max-size="maxSize"
ng-model="currentPage" class="pagination-sm" boundary-link-numbers="true" rotate="false"></uib-pagination>
Please try this
(function(){
var app = angular.module("sac.app", ['ui.bootstrap']);
app.controller('PatientController', ['$scope', function ($scope) {
$scope.patients = [{name:'A',age:25},{name:'B',age:26},{name:'F',age:28},{name:'N',age:50}];
$scope.sortType = 'name';
$scope.sortReverse = true;
$scope.search = '';
$scope.currentPage = 1;
$scope.numPerPage = 2;
$scope.totalItems = $scope.patients.length;
$scope.maxSize = 5;
var sortString = function(array, proName,desc){
array.sort(function(a, b){
var nameA=a[proName].toString().toLowerCase(), nameB=b[proName].toString().toLowerCase(), temp;
if(desc){
temp = nameA; nameA= nameB; nameB=temp;
}
if (nameA < nameB)
return -1
if (nameA > nameB)
return 1
return 0
});
};
sortString($scope.patients, 'name', $scope.sortReverse);
$scope.orderby = function(name){
$scope.currentPage = 1;
sortString($scope.patients, name, $scope.sortReverse)
};
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.patients.indexOf(value);
return (begin <= index && index < end);
};
}]);
}());
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" data-semver="3.3.6" data-require="bootstrap-css#*" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.js" data-semver="1.5.2" data-require="angular.js.1.3#*"></script>
<script data-require="ui-bootstrap#*" data-semver="1.3.2" src="https://cdn.rawgit.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-tpls-1.3.2.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="sac.app">
<div ng-controller="PatientController">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>
<a href="" ng-click="sortType = 'name'; sortReverse = !sortReverse; orderby('name')">
Name
<span ng-show="sortType == 'name'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
<th>
<a href="" ng-click="sortType = 'age'; sortReverse = !sortReverse; orderby('age')">
Age
<span ng-show="sortType == 'age'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="patient in patients | filter:paginate | filter:search">
<td>{{ patient.name }}</td>
<td>{{ patient.age }}</td>
</tr>
</tbody>
</table>
<uib-pagination first-text="Primera" last-text="Última" next-text=">" previous-text="<"
total-items="totalItems" items-per-page="numPerPage" max-size="maxSize"
ng-model="currentPage" class="pagination-sm" boundary-link-numbers="true" rotate="false"></uib-pagination>
</div>
</div>
</body>
</html>
(function(){
var app = angular.module("sac.app", ['ui.bootstrap']);
app.controller('PatientController', ['$scope', function ($scope) {
$scope.patients = [{name:'A',age:25},{name:'B',age:26},{name:'F',age:28},{name:'N',age:50}];
$scope.sortType = 'name';
$scope.sortReverse = true;
$scope.search = '';
$scope.currentPage = 1;
$scope.numPerPage = 2;
$scope.totalItems = $scope.patients.length;
$scope.maxSize = 5;
var sortString = function(array, proName,desc){
array.sort(function(a, b){
var nameA=a[proName].toString().toLowerCase(), nameB=b[proName].toString().toLowerCase(), temp;
if(desc){
temp = nameA; nameA= nameB; nameB=temp;
}
if (nameA < nameB)
return -1
if (nameA > nameB)
return 1
return 0
});
};
sortString($scope.patients, 'name', $scope.sortReverse);
$scope.orderby = function(name){
$scope.currentPage = 1;
sortString($scope.patients, name, $scope.sortReverse)
};
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.patients.indexOf(value);
return (begin <= index && index < end);
};
}]);
}());
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet" data-semver="3.3.6" data-require="bootstrap-css#*" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.js" data-semver="1.5.2" data-require="angular.js.1.3#*"></script>
<script data-require="ui-bootstrap#*" data-semver="1.3.2" src="https://cdn.rawgit.com/angular-ui/bootstrap/gh-pages/ui-bootstrap-tpls-1.3.2.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-app="sac.app">
<div ng-controller="PatientController">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>
<a href="" ng-click="sortType = 'name'; sortReverse = !sortReverse; orderby('name')">
Name
<span ng-show="sortType == 'name'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
<th>
<a href="" ng-click="sortType = 'age'; sortReverse = !sortReverse; orderby('age')">
Age
<span ng-show="sortType == 'age'" class="fa" ng-class="sortReverse ? 'fa-caret-up' : 'fa-caret-down'"></span>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="patient in patients | filter:paginate | filter:search">
<td>{{ patient.name }}</td>
<td>{{ patient.age }}</td>
</tr>
</tbody>
</table>
<uib-pagination first-text="Primera" last-text="Última" next-text=">" previous-text="<"
total-items="totalItems" items-per-page="numPerPage" max-size="maxSize"
ng-model="currentPage" class="pagination-sm" boundary-link-numbers="true" rotate="false"></uib-pagination>
</div>
</div>
</body>
</html>
Just write a custom filter function and do the paging, sorting and filtering manually in it.
I found this solution:
app.js
$scope.patients = data;
$scope.sortType = 'name'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.search = ''; // set the default search/filter term
$scope.currentPage = 1;
$scope.itemsPerPage = 5;
$scope.totalItems = $scope.patients.length;
$scope.maxSize = 5;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.itemsPerPage;
end = begin + $scope.itemsPerPage;
index = $scope.patients.indexOf(value);
return (begin <= index && index < end);
};
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.$watch('currentPage + itemsPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredFriends = $scope.patients.slice(begin, end);
});
$scope.noOfPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
$scope.$watch('search', function (newVal, oldVal) {
$scope.filtered = filterFilter($scope.patients, newVal);
$scope.totalItems = $scope.filtered.length;
$scope.noOfPages = Math.ceil($scope.totalItems / $scope.itemsPerPage);
$scope.currentPage = 1;
}, true);
patients.html
<tr ng-repeat="patient in filtered = patients | orderBy:sortType:sortReverse | filter:search | startFrom:(currentPage-1)*itemsPerPage | limitTo:itemsPerPage">
<td>{{ patient.name }} {{ patient.last_name }}</td>
<td>{{ patient.identity }}</td>
<td>{{ patient.age }}</td>
<td>{{ patient.telephone }}</td>
<td>{{ patient.email }}</td>
</tr>
<uib-pagination first-text="<<" last-text=">>" next-text=">" previous-text="<"
total-items="totalItems" items-per-page="itemsPerPage" max-size="noOfPages"
ng-model="currentPage" class="pagination-sm" boundary-link-numbers="true" rotate="false"></uib-pagination>
I have problem in pagination of my dataTable(angularJS),this is my code:
app.js:
.controller("StudentCtrl", ["$scope", "$http", "filterFilter", "$rootScope", "logger", "$filter", "$log", function($scope, $http, filterFilter, $rootScope, logger, $filter, $log) {
var init;
$scope.errors = [];
$scope.msgs = [];
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 1;
$http({method: 'GET', url: 'myURL'})
.success(function(data){
$scope.posts = data; // response data
$scope.searchKeywords = "", $scope.filteredStores = [], $scope.row = "", $scope.select = function(page) {
var end, start;
return start = (page - 1) * $scope.numPerPage, end = start + $scope.numPerPage, $scope.currentPageStores = $scope.filteredStores.slice(start, end);
}, $scope.onFilterChange = function() {
return $scope.select(1), $scope.currentPage = 1, $scope.row = "";
}, $scope.onNumPerPageChange = function() {
//console.log("2");
return $scope.select(1), $scope.currentPage =1 ;
}, $scope.onOrderChange = function() {
return $scope.select(1), $scope.currentPage;
}, $scope.search = function() {
return $scope.filteredStores = $filter("filter")(data, $scope.searchKeywords), $scope.onFilterChange();
}, $scope.order = function(rowName) {
return $scope.row !== rowName ? ($scope.row = rowName, $scope.filteredStores = $filter("orderBy")(data, rowName), $scope.onOrderChange()) : void 0;
}, $scope.numPerPageOpt = [3, 5, 10, 20], $scope.numPerPage = $scope.numPerPageOpt[2], $scope.currentPage = 1, $scope.currentPageStores = [], (init = function() {
return $scope.search(), $scope.select($scope.currentPage);
})()
}).error(function(data, status, headers, config) {
});
students.html
<div class="page page-table" ng-controller="StudentCtrl">
<section class="table-dynamic">
<div class="bs-component" >
<div class="bs-example table-dynamic">
<div class="table-filters">
<div class="row">
<div class="col-sm-4 col-xs-6">
<form>
<input type="text"
placeholder="search"
class="form-control"
ng-model="searchKeywords"
ng-keyup="search()" style="border-radius: 20px;">
</form>
</div>
<div class="col-sm-3 col-xs-6 filter-result-info">
<span>
Showing {{filteredStores.length}}/{{posts.length}} entries
</span>
</div>
</div>
</div>
<table class="table table-bordered table-responsive table-hover">
<thead>
<tr>
<th >Nom</th>
<th >Prenom </th>
<th >DropOut </th>
<th >Live </th>
<th >Classe</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="post in posts">
<td align="center">{{post.LastName}}</td>
<td align="center">{{post.FirstName}}</td>
<td align="center">{{post.DropOut}}</td>
<td align="center">{{post.Live}}</td>
<td align="center">{{post.Class}}</td>
<footer class="table-footer">
<div class="row">
<div class="col-md-6 page-num-info">
<span>
Show
<select data-ng-model="numPerPage"
data-ng-options="num for num in numPerPageOpt"
data-ng-change="onNumPerPageChange()">
</select>
entries per page
</span>
</div>
<div class="col-md-6 text-right pagination-container">
<pagination class="pagination-sm"
page="currentPage"
total-items="filteredStores.length"
max-size="4"
on-select-page="select(page)"
items-per-page="numPerPage"
rotate="true"
boundary-links="true"
></pagination>
</div>
</div>
</footer>
</div></div></section></div>
this is what I get per example when I select 5 rows from all data(8 rows):
and this is when I clic on second page of paginator:(I get the 5 first items all the time not the rest of 8 rows)
so how can I set the informations in table rows from the paginator
thanks a lot for help
Update:jsfiddle code:
https://jsfiddle.net/1982ybj6/
I am using angular datatable to display the response from the http request
I will send the request to web API that will communicate with the SQL Server database and gives the response
It is working fine for the response that are having the data, but for null response the datatable displayed in the UI is displaying the values from the previous response
Can anyone please help me to intimate like "There are no records inserted for the given request" when the response is null ?
Angular JS:
$scope.currentPage = 0; //current page
$scope.entryLimit = 10;
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < ($scope.filteredItems/$scope.entryLimit) - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
$scope.range = function (size,start, cu,elimit) {
var ret = [];
if( ($scope.filteredItems/$scope.entryLimit) < elimit)
{
if(($scope.filteredItems/$scope.entryLimit) ==0)
{
elimit = 1;
}
else
{
elimit = Math.ceil($scope.filteredItems/$scope.entryLimit);
}
}
var end = parseInt(cu)+parseInt(elimit);
console.log(size,start, end);
if (size < end) {
end = size;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
console.log(ret);
return ret;
};
HTML:
<div ng-show="filteredItems > 0">
<div class="col-md-2">PageSize:
<select ng-model="entryLimit" class="form-control">
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>
</div>
<div class="col-md-3">Filter:
<input type="text" ng-model="search" ng-change="filter()" placeholder="Filter" class="form-control" />
</div>
<div class="col-md-4">
<h5>Filtered {{ filtered.length }} of {{ totalItems}} total </h5>
</div>
</div>
<div>
<div class="col-md-12" ng-show="filteredItems > 0" >
<br/>
<br/>
<table class="table table-bordered table-striped table-hover " style=" outline: 1px solid orange;" >
<thead>
<tr>
<th ng-repeat="(key,value) in items[0]" ng-click="sort_by(key);" >{{key}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="items in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit ">
<td ng-repeat="(key,value) in items" > {{value}} </td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12" ng-show="filteredItems == 0">
<div class="col-md-12">
<h4>No details found</h4>
</div>
</div>
<div class="col-md-12" ng-show="filteredItems > 0 ">
<div 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(filteredItems, currentPage, currentPage , 5) "
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: (currentPage) == filteredItems - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</div>
</div>
</div>
My Http resonse will be resent in $scope.items.
Thanks
Looks like maybe you are keeping the response from the API call in $scope for longer than needed.
Destroy and refresh the model object in $scope prior to API call so that the $scope only has objects from the new response.
eg.
stories.destory()
In your controller, say your model
$scope.items.destroy();
// API call to receive results form server,
// now check if you received items response from server, if not display the message to the user.
Thanks,
Paul
Try to validate the response before populating the table...
Something like
if(response!== null){
$scope.items={};
return;
}
else{
$scope.items=response;
}
Almost everything working good beside 2 things
Code
var app = angular.module("MyApp", []);
app.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input.slice(start);
};
});
app.controller("MyControler", function($scope, $http, $filter) {
$http.get("http://127.0.0.1:8000/cars/?format=json").
success(function(data) {
$scope.list = data;
});
$scope.itemsPerPage = 1;
$scope.currentPage = 0;
$scope.items = [];
for (var i=0; i<50; i++) {
$scope.items.push({ id: i, name: "name "+ i, description: "description " + i });
}
$scope.range = function() {
var rangeSize = 3;
var ret = [];
var start;
start = $scope.currentPage;
if ( start > $scope.pageCount()-rangeSize ) {
start = $scope.pageCount()-rangeSize+1;
}
for (var i=start; i<start+rangeSize; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function() {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.prevPageDisabled = function() {
return $scope.currentPage === 0 ? "disabled" : "";
};
$scope.pageCount = function() {
return Math.ceil($scope.filtered.length/ $scope.itemsPerPage)-1;
};
$scope.nextPage = function() {
if ($scope.currentPage < $scope.pageCount()) {
$scope.currentPage++;
}
};
$scope.nextPageDisabled = function() {
return $scope.currentPage === $scope.pageCount() ? "disabled" : "";
};
$scope.setPage = function(n) {
$scope.currentPage = n;
};
var filterBy = $filter('filter');
$scope.$watch('search', function (newValue) { $scope.filtered = filterBy($scope.list, newValue); }, true);
});
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% verbatim %}
<div ng-app="MyApp" ng-controller="MyControler">
<table class="table table-striped">
<thead>
<tr>
<th><input ng-model="search.name" ></th>
<th><input ng-model="search.years"></th>
<th><input ng-model="search.owners"></th>
<th><input ng-model="search.accidents"></th>
<th><input ng-model="search.description"></th>
</tr>
<tr>
<th>Name</th>
<th>Years</th>
<th>Owners</th>
<th>Accidents</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cars in filtered| offset:currentPage*itemsPerPage | limitTo: itemsPerPage">
<td>{{cars.name}}</td>
<td>{{cars.years}}</td>
<td>{{cars.owners}}</td>
<td>{{cars.accidents}}</td>
<td>{{cars.description}}</td>
</tr>
</tbody>
<tfoot>
<td colspan="3">
<div class="pagination">
<ul>
<li ng-class="prevPageDisabled()">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range()" ng-class="{active: n == currentPage}" ng-click="setPage(n)">
{{n+1}}
</li>
<li ng-class="nextPageDisabled()">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</td>
</tfoot>
</table>
</div>
{% endverbatim %}
</body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="{% static 'js/app2.js' %}"></script>
</html>
My objects are displayed only when i start typing into filter field, as i see after pagination is updated actively with typing but then happening sth strange, pagination displayed also pages with minuses ?
So i would like to make items showed already without starting typing into filter and make these minuses disappear.
Thanks ;)
var app=angular.module('MyApp', []);
app.controller("MyControler", function($scope, $http, $filter) {
$http.get("http://127.0.0.1:8000/cars/?format=json").
success(function(data) {
$scope.list = data;
});
$scope.currentPage = 0;
$scope.pageSize = 1;
$scope.numberOfPages=function(){
var myFilteredData = $filter('filter')($scope.list, $scope.search);
return Math.ceil(myFilteredData.length/$scope.pageSize);
};
});
app.filter("offset", function() {
return function(input, start) {
start = +start;
return input.slice(start);
};
});
<!DOCTYPE html>
{% load staticfiles %}
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
{% verbatim %}
<div ng-app="MyApp" ng-controller="MyControler">
<table>
<tr>
<th><input type="text" ng-model="search.name" class="form-control input-sm" placeholder="SEARCH" ></th>
<th><input type="text" ng-model="search.years" class="form-control input-sm" placeholder="SEARCH"></th>
<th><input type="text" ng-model="search.owners" class="form-control input-sm" placeholder="SEARCH"></th>
<th><input type="text" ng-model="search.accidents" class="form-control input-sm" placeholder="SEARCH"></th>
<th><input type="text" ng-model="search.description" class="form-control input-sm" placeholder="SEARCH"></th>
</tr>
<tr>
<th>Name</th>
<th>Years</th>
<th>Owners</th>
<th>Accidents</th>
<th>Description</th>
</tr>
<tr ng-repeat="cars in list | filter:search|offset:currentPage*pageSize | limitTo:pageSize">
<td>{{cars.name}}</td>
<td>{{cars.years}}</td>
<td>{{cars.owners}}</td>
<td>{{cars.accidents}}</td>
<td>{{cars.description}}</td>
</tr>
</table>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">
Previous
</button>
{{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="(currentPage + 1) == numberOfPages()" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
{% endverbatim %}
</body>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="{% static 'js/app2.js' %}"></script>
</html>
Solved