AngularJs Sorting across all the pages - angularjs

Can anybody help me with angularjs sorting across all the pages when I am using Server side pagination and sorting.
I am using ui-bootsrap for pagination;
Code as attached.
My sorting is happening only once in ascending order.Any idea how to sort in both direction ? i.e i m passing the sortBy as +property to sort i need to toggle the property with - infront once its sorted in asc order. Any directive to handle that toggle?
$scope.maxSize = 5;
$scope.currentPage = 1;
$scope.itemsPerPage = 5;
//This method gets called each time the page is loaded or move to next page
$scope.isResultExist = function (list) {
$scope.list = list;
return $scope.populateResult();
};
$scope.populateResult = function () {
if ($scope.list != undefined) {
$scope.totalItems = $scope.list.length;
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
, end = begin + $scope.itemsPerPage;
$scope.result = $scope.list.slice(begin, end);
}
};
$scope.sort_by = function (sortBy) {
if ($scope.list != undefined) {
var sortOrder = 1;
$log.debug("**************list : " + $scope.list);
$scope.list.sort(function (a, b) {
for (var k = 0; k < $scope.list.length; k++) {
var valueA = a[sortBy];
var valueB = b[sortBy];
var result = (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0;
return result * sortOrder;
}
});
$scope.populateResult();
}
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<th class="source"><a href="#" ng-click="sort_by('source')" data-toggle="tooltip" bs-tooltip
data-title="sort by Source ID">Source ID<i class="fa fa-sort"></i>
</a></th>
<tr data-ng-repeat="keyRingItem in result ">
Pagination:
<pagination items-per-page="itemsPerPage" total-items="totalItems" ng-model="currentPage"
max-size="maxSize" class="pagination-sm" boundary-links="true">
</pagination>

If your paging is being done server-side, then the sorting must be done server-side.
Angular will only be able to sort the page of data that it has.
Either implement the sorting server-side, or retrieve all data and implement the paging client-side.

$scope.propertyName = 'age';//Amol sorting angularjs
$scope.reverse = true;
$scope.Shiftsort = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
angular.module('orderByExample2', [])
.controller('ExampleController', ['$scope', function($scope) {
var friends = [
{name: 'John', phone: '555-1212', age: 10},
{name: 'Mary', phone: '555-9876', age: 19},
{name: 'Mike', phone: '555-4321', age: 21},
{name: 'Adam', phone: '555-5678', age: 35},
{name: 'Julie', phone: '555-8765', age: 29}
];
$scope.propertyName = 'age';
$scope.reverse = true;
$scope.friends = friends;
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
}]);
.friends {
border-collapse: collapse;
}
.friends th {
border-bottom: 1px solid;
}
.friends td, .friends th {
border-left: 1px solid;
padding: 5px 10px;
}
.friends td:first-child, .friends th:first-child {
border-left: none;
}
.sortorder:after {
content: '\25b2'; // BLACK UP-POINTING TRIANGLE
}
.sortorder.reverse:after {
content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<div ng-controller="ExampleController">
<pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
<hr/>
<button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
<hr/>
<table class="friends">
<tr>
<th>
<button ng-click="sortBy('name')">Name</button>
<span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('phone')">Phone Number</button>
<span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('age')">Age</button>
<span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>

Related

Angular JS Table Formatting

I have a AngularJS application in which I have a table as You can see in the image below,
as you can see the last column contains a delete and and a edit button for every row. How can I highlight row when the corresponding delete button is pressed?
Here is my code: https://plnkr.co/edit/ZNzgVO59eWJSVMH7?preview
var myApp = angular.module('myApp', []);
myApp.constant('Employees',
[{ Name: "Ishan", Code: 1, Is_Intern: "Yes", DateOfJoining: "01/02/2022", Skills: "VB, DOT.NET, Angular", Status: "Working" },
{ Name: "Ashwin", Code: 2, Is_Intern: "No", DateOfJoining: "21/03/2021", Skills: "VB, Ruby, Angular", Status: "Inactive" },
{ Name: "Shailesh", Code: 3, Is_Intern: "Yes", DateOfJoining: "27/04/2021", Skills: "VB, Python, Angular", Status: "Working" },
{ Name: "Pawan", Code: 4, Is_Intern: "No", DateOfJoining: "14/01/2022", Skills: "VB, Sapphire, Angular", Status: "Inactive" }]);
myApp.component('employeeDetail', {
bindings: {
Name: '<',
Code: '<',
Is_Intern: '<',
DateOfJoining: '<',
Skills: '<',
},
controller: 'empCtrl',
});
myApp.controller('empCtrl', function empCtrl($scope, Employees) {
$scope.EmployeeDetails = Employees;
$scope.Name = Employees.Name;
$scope.Code = Employees.Code;
$scope.Is_Intern = Employees.Is_Intern;
$scope.DateOfJoining = Employees.DateOfJoining;
$scope.Skills = Employees.Skills;
$scope.Status = Employees.Status;
$scope.add = function () {
$scope.EmployeeDetails.push({
Name: $scope.Name,
Code: $scope.Code,
Is_Intern: $scope.Is_Intern,
DateOfJoining: $scope.DateOfJoining,
Skills: $scope.Skills,
Status: $scope.Status,
});
$scope.id = '';
$scope.Code = '';
$scope.Is_Intern = '';
$scope.DateOfJoining = '';
$scope.Skills = '';
$scope.Status = '';
};
function select(Name) {
for (let i = 0; i < $scope.EmployeeDetails.length; i++) {
if ($scope.EmployeeDetails[i].Name == Name) {
return i;
}
}
return -1;
};
$scope.edit = function (Name) {
let index = select(Name);
let emp = $scope.EmployeeDetails[index];
$scope.Name = emp.Name;
$scope.Code = emp.Code;
$scope.Is_Intern = emp.Is_Intern;
$scope.DateOfJoining = emp.DateOfJoining;
$scope.Skills = emp.Skills;
$scope.Status = emp.Status;
}
$scope.save = function () {
let index = select($scope.Name);
$scope.EmployeeDetails[index].Name = $scope.Name;
$scope.EmployeeDetails[index].Code = $scope.Code;
$scope.EmployeeDetails[index].Is_Intern = $scope.Is_Intern;
$scope.EmployeeDetails[index].DateOfJoining = $scope.DateOfJoining;
$scope.EmployeeDetails[index].Skills = $scope.Skills;
$scope.EmployeeDetails[index].Status = $scope.Status;
$scope.Name = '';
$scope.Code = '';
$scope.Is_Intern = '';
$scope.DateOfJoining = '';
$scope.Skills = '';
$scope.Status = '';
}
$scope.delete = function (emp) {
if (confirm("Are You Sure You want to delete this record ?")) {
$scope.EmployeeDetails.splice(emp, 1)
alert("Deleted")
}
}
$scope.selectedRow = null;
$scope.setClickedRow = function (index) {
$scope.selectedRow = index;
}
});
table {
border-collapse: collapse;
font-family: Arial;
}
td {
border: 1px solid black;
padding: 5px;
}
th {
border: 1px solid black;
padding: 5px;
text-align: center;
}
label,
input {
display: block;
}
label {
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="myApp" ng-controller="empCtrl">
<table>
<thead>
<th colspan="8">Names of Employees</th>
</thead>
<tbody>
<tr>
<th>Name</th>
<th>Code</th>
<th>Is_Intern</th>
<th>Skills</th>
<th>Status</th>
<th>DateOfJoining</th>
<th colspan="2" style="text-align: center;">Action</th>
</tr>
<tr ng-repeat="emp in EmployeeDetails">
<td>{{emp.Name}}</td>
<td>{{emp.Code}}</td>
<td>{{emp.Is_Intern}}</td>
<td>{{emp.Skills}}</td>
<td>{{emp.Status}}</td>
<td>{{emp.DateOfJoining}}</td>
<td><button ng-click="edit(emp.Name)">Edit</button></td>
<td><button ng-click="delete($index)">Delete</button></td>
</tr>
</tbody>
<label>
Name
<input ng-model="Name" type="text" />
</label>
<label>
Code
<input ng-model="Code" type="number" />
</label>
<label>
Is_Intern
<input ng-model="Is_Intern" type="text" />
</label>
<label>
Skills
<input ng-model="Skills" type="text" />
</label>
<label>
Status
<input ng-model="Status" type="text" />
</label>
<label>
Date Of Joining
<input ng-model="DateOfJoining" type="text" />
</label>
<label>
<button ng-click="add()">Add</button>
</label>
<button ng-click="save()">Update</button><br><br>
</table>
<br>
</body>
This can be achieved by using ng-class in angular js.
Logic.
On delete button click set some flag on the row to indicate that the row is active I used an isActive class.
Then use a ng-class condition, ng-class="{'highlight': emp.isActive == true}".
Since you are making use of a JavaScript confirm method, you have to use a setTimeout function to trigger the confirm dialog. Or else the changes will not be visible in the DOM.
Since you have used setTimeout, you have to use $scope.$apply() to get your changes reflected in the UI.
Working Fiddle.
var myApp = angular.module('myApp', []);
myApp.constant('Employees',
[{ Name: "Ishan", Code: 1, Is_Intern: "Yes", DateOfJoining: "01/02/2022", Skills: "VB, DOT.NET, Angular", Status: "Working" },
{ Name: "Ashwin", Code: 2, Is_Intern: "No", DateOfJoining: "21/03/2021", Skills: "VB, Ruby, Angular", Status: "Inactive" },
{ Name: "Shailesh", Code: 3, Is_Intern: "Yes", DateOfJoining: "27/04/2021", Skills: "VB, Python, Angular", Status: "Working" },
{ Name: "Pawan", Code: 4, Is_Intern: "No", DateOfJoining: "14/01/2022", Skills: "VB, Sapphire, Angular", Status: "Inactive" }]);
myApp.component('employeeDetail', {
bindings: {
Name: '<',
Code: '<',
Is_Intern: '<',
DateOfJoining: '<',
Skills: '<',
},
controller: 'empCtrl',
});
myApp.controller('empCtrl', function empCtrl($scope, Employees) {
$scope.EmployeeDetails = Employees;
$scope.Name = Employees.Name;
$scope.Code = Employees.Code;
$scope.Is_Intern = Employees.Is_Intern;
$scope.DateOfJoining = Employees.DateOfJoining;
$scope.Skills = Employees.Skills;
$scope.Status = Employees.Status;
$scope.add = function () {
$scope.EmployeeDetails.push({
Name: $scope.Name,
Code: $scope.Code,
Is_Intern: $scope.Is_Intern,
DateOfJoining: $scope.DateOfJoining,
Skills: $scope.Skills,
Status: $scope.Status,
});
$scope.id = '';
$scope.Code = '';
$scope.Is_Intern = '';
$scope.DateOfJoining = '';
$scope.Skills = '';
$scope.Status = '';
};
function select(Name) {
for (let i = 0; i < $scope.EmployeeDetails.length; i++) {
if ($scope.EmployeeDetails[i].Name == Name) {
return i;
}
}
return -1;
};
$scope.edit = function (Name) {
let index = select(Name);
let emp = $scope.EmployeeDetails[index];
$scope.Name = emp.Name;
$scope.Code = emp.Code;
$scope.Is_Intern = emp.Is_Intern;
$scope.DateOfJoining = emp.DateOfJoining;
$scope.Skills = emp.Skills;
$scope.Status = emp.Status;
}
$scope.save = function () {
let index = select($scope.Name);
$scope.EmployeeDetails[index].Name = $scope.Name;
$scope.EmployeeDetails[index].Code = $scope.Code;
$scope.EmployeeDetails[index].Is_Intern = $scope.Is_Intern;
$scope.EmployeeDetails[index].DateOfJoining = $scope.DateOfJoining;
$scope.EmployeeDetails[index].Skills = $scope.Skills;
$scope.EmployeeDetails[index].Status = $scope.Status;
$scope.Name = '';
$scope.Code = '';
$scope.Is_Intern = '';
$scope.DateOfJoining = '';
$scope.Skills = '';
$scope.Status = '';
}
$scope.deleteRow = function (emp, row) {
row.isActive = true;
setTimeout(function () {
$scope.delete(emp, row);
});
}
$scope.delete = function (emp, row) {
if (confirm("Are You Sure You want to delete this record ?")) {
$scope.EmployeeDetails.splice(emp, 1)
$scope.$apply();
alert("Deleted");
}
row.isActive = false;
}
$scope.selectedRow = null;
$scope.setClickedRow = function (index) {
$scope.selectedRow = index;
}
});
table {
border-collapse: collapse;
font-family: Arial;
}
td {
border: 1px solid black;
padding: 5px;
}
th {
border: 1px solid black;
padding: 5px;
text-align: center;
}
label,
input {
display: block;
}
label {
margin-bottom: 5px;
}
.highlight {
background: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<body ng-app="myApp" ng-controller="empCtrl">
<table>
<thead>
<th colspan="8">Names of Employees</th>
</thead>
<tbody>
<tr>
<th>Name</th>
<th>Code</th>
<th>Is_Intern</th>
<th>Skills</th>
<th>Status</th>
<th>DateOfJoining</th>
<th colspan="2" style="text-align: center;">Action</th>
</tr>
<tr ng-repeat="emp in EmployeeDetails" ng-class="{'highlight': emp.isActive == true}">
<td>{{emp.Name}} - {{ emp.isActive }}</td>
<td>{{emp.Code}}</td>
<td>{{emp.Is_Intern}}</td>
<td>{{emp.Skills}}</td>
<td>{{emp.Status}}</td>
<td>{{emp.DateOfJoining}}</td>
<td><button ng-click="edit(emp.Nam, emp)">Edit</button></td>
<td><button ng-click="deleteRow($index, emp)">Delete</button></td>
</tr>
</tbody>
<label>
Name
<input ng-model="Name" type="text" />
</label>
<label>
Code
<input ng-model="Code" type="number" />
</label>
<label>
Is_Intern
<input ng-model="Is_Intern" type="text" />
</label>
<label>
Skills
<input ng-model="Skills" type="text" />
</label>
<label>
Status
<input ng-model="Status" type="text" />
</label>
<label>
Date Of Joining
<input ng-model="DateOfJoining" type="text" />
</label>
<label>
<button ng-click="add()">Add</button>
</label>
<button ng-click="save()">Update</button><br><br>
</table>
<br>
</body>

How to Filter table data with AngularJs if column_name is double time?

I use AngularJs and I have the below code :
<tr ng-repeat=" a in table>
<td>{{a.ClientID}}</td>
<td>{{a.SiteName}}</td>
<td>{{a.Group}}</td>
</tr>
the result of this table is:
ClientID SiteName Group
========= ========== =======
1 Ikaria Group
2 Ikaria Group
3 Limnos Null
4 Pythion Group
I want to create a filter when AlarmGroup = Group and SiteName multiple times gives me below result :
ClientID SiteName Group
========= ========== =======
1 (+) Ikaria Group
3 Limnos Null
4 Pythion Group
When I click ClientID (+) I want to see and row with ClientID = 2
Do you have any idea ?
Thanks!!
You can easily acieve that using custom unique filter.
Here is the working code
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
var app = angular.module("testApp", ['ui.bootstrap']);
app.controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.showDupes = function(site){
if($scope.siteName == site){
$scope.siteName = undefined;
}
else{
$scope.siteName = site;
}
};
$scope.filter='SiteName';
$scope.getCount = function(i) {
var iCount = iCount || 0;
for (var j = 0; j < $scope.tableData.length; j++) {
if ($scope.tableData[j].SiteName == i) {
iCount++;
}
}
return iCount;
}
$scope.tableData = [{"ClientID":1,"SiteName":"Ikaria","Group":"Group"},{"ClientID":2,"SiteName":"Ikaria","Group":"Group"},{"ClientID":3,"SiteName":"Limnos","Group":"Null"},{"ClientID":4,"SiteName":"Limnos","Group":"Null"},{"ClientID":5,"SiteName":"Limnos","Group":"Null"},{"ClientID":6,"SiteName":"Limnos","Group":"Null"},{"ClientID":7,"SiteName":"Limnos","Group":"Null"},{"ClientID":8,"SiteName":"Pythion","Group":"Group"}];
}]);
app.filter('unique', function() {
return function(items, filterOn, dupe) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {},
newItems = [];
var extractValueToCompare = function(item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function(item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (newItems[i][filterOn] != dupe && angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
item.isDuplicate = isDuplicate;
newItems.push(item);
});
items = newItems;
}
return items;
};
});
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<table class="table">
<tr ng-repeat="a in tableData | unique:filter:siteName as filteredTable" ng-hide="a.isDuplicate">
<td>{{a.ClientID}}</td>
<td>
{{a.SiteName}}
<button ng-show="getCount(a.SiteName)> 1 && a.SiteName != siteName" ng-click="showDupes(a.SiteName)">+ {{getCount(a.SiteName)-1}}</button>
</td>
<td>{{a.Group}}</td>
</tr>
</table>
<button ng-click="showDupes(undefined)">Reset</button>
</div>
</body>
</html>
angular.module('app', []).controller('ctrl', function($scope){
$scope.data = [
{ClientID:1, SiteName: 'Ikaria', Group: 'Group'},
{ClientID:2, SiteName: 'Ikaria', Group: 'Group'},
{ClientID:3, SiteName: 'Ikaria', Group: 'Group'},
{ClientID:4, SiteName: 'Limnos', Group: 'Null'},
{ClientID:5, SiteName: 'Pythion', Group: 'Group'},
{ClientID:6, SiteName: 'Pythion', Group: 'Group'},
{ClientID:7, SiteName: 'Test', Group: 'Null'}
];
})
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-app='app' ng-controller='ctrl'>
<thead>
<tr>
<td>ClientID</td>
<td>SiteName</td>
<td>Group</td>
</tr>
</thead>
<tbody>
<tr ng-repeat='item in (data | orderBy: "Group") | orderBy: "SiteName"' ng-if='$first || item.SiteName != data[$index-1].SiteName || item.Group != data[$index-1].Group || this[item.SiteName + item.Group]'>
<td>
{{item.ClientID}}
<a href='#' type='button' ng-if='((data | filter: {SiteName : item.SiteName}) | filter: {Group : item.Group}).length > 1 && !this[item.SiteName + item.Group]' ng-click='$parent.$parent.$parent[item.SiteName + item.Group]=true'>(+)</a>
</td>
<td>{{item.SiteName}}</td>
<td>{{item.Group}}</td>
</tr>
<tbody>
</table>

How to use $http service of angularjs to get data from mongodb using node js code

//Here is my angular app now i want to get mongodb data in json using node how to use $http service
<tr ng-repeat="x in ItemsByPage[currentPage] | orderBy:columnToOrder:reverse">
<td >{{x.id}}</td> // how to get data here from a json data of mongodb
<td >
<!-- editable username (text with validation) -->
<span editable-text="x.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, x.id)" e-required>
{{ x.name || 'empty' }}
</span>
</td>
<td>
<!-- editable status (select-local) -->
<span editable-text="x.lName" e-name="lName" e-form="rowform">
{{ x.lName || 'empty' }}
</span>
</td>
<td >
<!-- editable group (select-remote) -->
<span editable-text="x.pages" e-name="pages" e-form="rowform" >
{{ x.pages || 'empty' }}
</span>
</td>
<td>
<span editable-text="x.passw1" e-name="passw1" e-form="rowform" >
{{x.passw1 || 'empty'}}
</span>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" ng-show="rowform.$visible" class="form-buttons form-inline">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeUser($index)">del</button>
</div>
</td>
</tr>
</table>
<button class="btn btn-default" ng-click="addUser()">Add row</button>
<br>
<ul class="pagination pagination-sm">
<li ng-class="{active:0}">First
</li>
<li ng-repeat="n in range(ItemsByPage.length)"> 1
</li>
<li>Last
</li>
</ul>
</div>
<button type="button" onclick="loadDoc(this.value)">Change Content</button>
<!-- <div id="txtHint">Customer info will be listed here...</div> -->
View Records
<script>
var app = angular.module("app", ["xeditable", "ngMockE2E"]);
app.service('filteredListService', function () {
this.searched = function (valLists,toSearch) {
return _.filter(valLists,
function (i) {
/* Search Text in all 3 fields */
return searchUtil(i, toSearch);
});
};
this.paged = function (valLists,pageSize)
{
retVal = [];
for (var i = 0; i < valLists.length; i++) {
if (i % pageSize === 0) {
retVal[Math.floor(i / pageSize)] = [valLists[i]];
} else {
retVal[Math.floor(i / pageSize)].push(valLists[i]);
}
}
return retVal;
};
});
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', function($scope, $filter, filteredListService) {
$scope.users = [
{id:1, name:'harry potter', lName:"Pege" ,passw1:"12/12/2012",pages:"556"},
{id:2, name:'narnia', lName:"Pim" ,passw1:"12/12/2012",pages:"557"},
{id:3, name:'panchtantra', lName:"Smith" ,passw1:"1/03/2009",pages:"556"},
{id:4, name:'atlas', lName:"Jones" ,passw1:"2/04/1995",pages:"888"},
{id:5, name:'science', lName:"Doe" ,passw1:"2/04/1995",pages:"888"},
{id:6, name:'guiness book',lName:"Pan" ,passw1:"2/04/1995",pages:"888"},
{id:7, name:'panchtantra1', lName:"Smith" ,passw1:"1/03/2009",pages:"556"},
{id:8, name:'atlas1', lName:"Jones" ,passw1:"2/04/1995",pages:"888"},
{id:9, name:'science1', lName:"Doe" ,passw1:"2/04/1995",pages:"888"},
{id:10, name:'guiness book1',lName:"Pan" ,passw1:"2/04/1995",pages:"888"},
];
$scope.checkName = function(data, id) {
if (id === 2 && data !== 'narnia') {
return "Username 2 should be `narnia(case sensitive)`";
}
};
$scope.saveUser = function(data, id) {
//$scope.user not updated yet
angular.extend(data, {id: id});
return $http.post('/saveUser', data);
};
// remove user
$scope.removeUser = function(index) {
var index1 = index + $scope.currentPage * 4;
$scope.users.splice(index1,1);
$scope.pagination();
};
// add user
$scope.addUser = function($event) {
$scope.currentPage = 2;
$scope.id= $scope.users.length + 1
$scope.users.push({
id:this.id,
name:'Enter Book Name',
lName:'Author Name',
passw1:'Date of Publish',
pages:'Pages'
});
$scope.pagination();
alert(users.id);
$scope.resetAll();
}
//search
$scope.pageSize = 4;
$scope.allItems = $scope.users;
$scope.reverse = false;
$scope.resetAll = function () {
$scope.filteredList = $scope.allItems;
$scope.newEmpId = '';
$scope.newName = '';
$scope.newEmail = '';
$scope.searchText = '';
$scope.currentPage = 0;
$scope.Header = ['','',''];
}
//pagination
$scope.pagination = function () {
$scope.ItemsByPage = filteredListService.paged( $scope.filteredList, $scope.pageSize );
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
$scope.firstPage = function () {
$scope.currentPage = 0;
};
$scope.lastPage = function () {
$scope.currentPage = $scope.ItemsByPage.length - 1;
};
$scope.range = function (input, total) {
var ret = [];
if (!total) {
total = input;
input = 0;
}
for (var i = input; i < total; i++) {
if (i != 0 && i != total - 1) {
ret.push(i);
}
}
return ret;
};
$scope.sort = function(sortBy){
$scope.resetAll();
$scope.pagination();
};
$scope.sort ('name');
$scope.search = function () {
$scope.filteredList =
filteredListService.searched($scope.allItems, $scope.searchText);
if ($scope.searchText == '') {
$scope.filteredList = $scope.allItems;
}
$scope.pagination();
}
$scope.resetAll();
});
function searchUtil(x,toSearch)
{
/* Search Text in all 3 fields */
return ( x.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || x.lName.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || x.id == toSearch
)
? true : false ;
}
</script>
</body>
</html>
//here it is my nodejs file.how to get data from /view-feedbacks in my angularjs .i am a tyro to this.please help me out with $http service only.thereafter how to use ng-repeat to get that data in table.
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
var dd=db.db("book");
dd.collection('users').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
});
});
app.listen(process.env.PORT || 3100, process.env.IP || '0.0.0.0' );
Is your nodejs code is correct.
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
var dd=db.db("book"); // not sure of this line, it depends on how you started.
dd.collection('users').find().toArray().then(function(err, feedbacks) { // the first parameter will always be err
console.log("feedbacks",feedbacks);//check whether you are getting feedbacks from your mongodb
res.send(feedbacks); //no need for status here
});
});
});

Add a class selectively to an ng-repeat AngularJS

I have an ng-repeat for a table, I want to be able to add a class when <td> is clicked, and remove the class when un-clicked. Multiple <td> can be selected at the same time. Right now ALL of the cities are or are not getting the class applies.
For example: (lets say nodes has 100 items)
<tr ng-repeat node in nodes>
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="toggleMe( node.city )" ng-class"{clicked : isClicked()}" >{{node.city}}</td>
</tr>
in my JS
$scope.cityArr = [];
$scope.toggleMe = function(city) {
if ($scope.count > 0) {
angular.forEach($scope.cityArr, function(value) {
if (city === value) {
$scope.clicked = false;
} else {
$scope.cityArr.push(city);
$scope.clicked = true;
}
});
} else {
$scope.cityArr.push(city);
$scope.clicked = true;
}
$scope.count = 1;
};
$scope.isClicked = function() {
return $scope.clicked;
};
Right now there is a single clicked property on the scope that you're changing and everything refers to that. Try to put clicked on the node instead...
$scope.toggleMe = function(node) {
if ($scope.count > 0) {
angular.forEach($scope.cityArr, function(value) {
if (node.city === value) {
node.clicked = false;
} else {
$scope.cityArr.push(node.city);
node.clicked = true;
}
});
} else {
$scope.cityArr.push(node.city);
node.clicked = true;
}
$scope.count = 1;
};
And in the ngRepeat...
<tr ng-repeat node in nodes>
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="toggleMe( node )" ng-class"{clicked : node.clicked}" >{{node.city}}</td>
</tr>
You don't need a special function or controller to accomplish this:
<table>
<tbody>
<tr ng-repeat="node in nodes">
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="node.highlight = !node.highlight"
ng-class="{ highlight: node.highlight }">
{{node.city}}
</td>
</tr>
</tbody>
</table>
Full Plunker example: http://plnkr.co/edit/1hdcIOfz0nHb91uFWKrv
I could show you the controller I used by it's empty except for the test data. You don't need a function.
Alternately, the code can use a separate array and $index to set classes:
<tr ng-repeat="node in nodes"
ng-class="{ highlight: highlightRows[$index] }">
<td class="x" ng-click="toggleHighlight($index)">
X
</td>
This approach is useful if you want to separate Model data from View data.
The DEMO
angular.module("app", [])
.controller("TestController", function($scope) {
$scope.highlightRows = [];
$scope.toggleHighlight = function(idx) {
$scope.highlightRows[idx] = !$scope.highlightRows[idx];
};
$scope.nodes = [
{ name: "Alpha", date: new Date(), city: "Omaha" },
{ name: "Bravo", date: new Date(), city: "New York" },
{ name: "Charlie", date: new Date(), city: "Minneapolis" }
];
})
table {
border-collapse: collapse;
font-family: sans-serif;
}
td {
padding: 5px;
border: solid black 1px;
}
.x {
cursor: pointer;
}
.highlight {
background: yellow;
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="TestController">
<table>
<h3>Click on X to highlight</h3>
<tbody>
<tr ng-repeat="node in nodes"
ng-class="{ highlight: highlightRows[$index] }">
<td class="x" ng-click="toggleHighlight($index)">
X
</td>
<td>{{node.name}}</td>
<td>{{node.date | date}}</td>
<td>{{node.city}}</td>
</tr>
</tbody>
</table>
highlightRows={{highlightRows}}
</body>

How to do paging in AngularJS?

I have a dataset of about 1000 items in-memory and am attempting to create a pager for
this dataset, but I'm not sure on how to do this.
I'm using a custom filter function to filter the results, and that works fine, but somehow I need to get the number of pages out.
Any clues?
Angular UI Bootstrap - Pagination Directive
Check out UI Bootstrap's pagination directive. I ended up using it rather than what is posted here as it has enough features for my current use and has a thorough test spec to accompany it.
View
<!-- table here -->
<pagination
ng-model="currentPage"
total-items="todos.length"
max-size="maxSize"
boundary-links="true">
</pagination>
<!-- items/page select here if you like -->
Controller
todos.controller("TodoController", function($scope) {
$scope.filteredTodos = []
,$scope.currentPage = 1
,$scope.numPerPage = 10
,$scope.maxSize = 5;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:"todo "+i, done:false});
}
};
$scope.makeTodos();
$scope.$watch("currentPage + numPerPage", function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
});
});
I have made a working plunker for reference.
Legacy Version:
View
<!-- table here -->
<div data-pagination="" data-num-pages="numPages()"
data-current-page="currentPage" data-max-size="maxSize"
data-boundary-links="true"></div>
<!-- items/page select here if you like -->
Controller
todos.controller("TodoController", function($scope) {
$scope.filteredTodos = []
,$scope.currentPage = 1
,$scope.numPerPage = 10
,$scope.maxSize = 5;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:"todo "+i, done:false});
}
};
$scope.makeTodos();
$scope.numPages = function () {
return Math.ceil($scope.todos.length / $scope.numPerPage);
};
$scope.$watch("currentPage + numPerPage", function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage)
, end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
});
});
I have made a working plunker for reference.
I recently implemented paging for the Built with Angular site. You chan checkout the source: https://github.com/angular/builtwith.angularjs.org
I'd avoid using a filter to separate the pages. You should break up the items into pages within the controller.
I've had to implement pagination quite a few times with Angular, and it was always a bit of a pain for something that I felt could be simplified. I've used some of the ideas presented here and elsewhere to make a pagination module that makes pagination as simple as:
<ul>
<li dir-paginate="item in items | itemsPerPage: 10">{{ item }}</li>
</ul>
// then somewhere else on the page ....
<dir-pagination-controls></dir-pagination-controls>
That's it. It has the following features:
No custom code needed in your controller to tie the collection items to the pagination links.
You aren't bound to using a table or gridview - you can paginate anything you can ng-repeat!
Delegates to ng-repeat, so you can use any expression that could be validly used in an ng-repeat, including filtering, ordering etc.
Works across controllers - the pagination-controls directive does not need to know anything about the context in which the paginate directive is called.
Demo : http://plnkr.co/edit/Wtkv71LIqUR4OhzhgpqL?p=preview
For those who are looking for a "plug and play" solution, I think you'll find this useful.
Code
The code is available here on GitHub and includes a pretty good set of tests:
https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
If you are interested I also wrote a short piece with a little more insight into the design of the module: http://www.michaelbromley.co.uk/blog/108/paginate-almost-anything-in-angularjs/
I just made a JSFiddle that show pagination + search + order by on each column using btford code: http://jsfiddle.net/SAWsA/11/
I updated Scotty.NET's plunkr http://plnkr.co/edit/FUeWwDu0XzO51lyLAEIA?p=preview so that it uses newer versions of angular, angular-ui, and bootstrap.
Controller
var todos = angular.module('todos', ['ui.bootstrap']);
todos.controller('TodoController', function($scope) {
$scope.filteredTodos = [];
$scope.itemsPerPage = 30;
$scope.currentPage = 4;
$scope.makeTodos = function() {
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:'todo '+i, done:false});
}
};
$scope.figureOutTodosToDisplay = function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage);
var end = begin + $scope.itemsPerPage;
$scope.filteredTodos = $scope.todos.slice(begin, end);
};
$scope.makeTodos();
$scope.figureOutTodosToDisplay();
$scope.pageChanged = function() {
$scope.figureOutTodosToDisplay();
};
});
Bootstrap UI component
<pagination boundary-links="true"
max-size="3"
items-per-page="itemsPerPage"
total-items="todos.length"
ng-model="currentPage"
ng-change="pageChanged()"></pagination>
This is a pure javascript solution that I've wrapped as an Angular service to implement pagination logic like in google search results.
Working demo on CodePen at http://codepen.io/cornflourblue/pen/KVeaQL/
Details and explanation at this blog post
function PagerService() {
// service definition
var service = {};
service.GetPager = GetPager;
return service;
// service implementation
function GetPager(totalItems, currentPage, pageSize) {
// default to first page
currentPage = currentPage || 1;
// default page size is 10
pageSize = pageSize || 10;
// calculate total pages
var totalPages = Math.ceil(totalItems / pageSize);
var startPage, endPage;
if (totalPages <= 10) {
// less than 10 total pages so show all
startPage = 1;
endPage = totalPages;
} else {
// more than 10 total pages so calculate start and end pages
if (currentPage <= 6) {
startPage = 1;
endPage = 10;
} else if (currentPage + 4 >= totalPages) {
startPage = totalPages - 9;
endPage = totalPages;
} else {
startPage = currentPage - 5;
endPage = currentPage + 4;
}
}
// calculate start and end item indexes
var startIndex = (currentPage - 1) * pageSize;
var endIndex = startIndex + pageSize;
// create an array of pages to ng-repeat in the pager control
var pages = _.range(startPage, endPage + 1);
// return object with all pager properties required by the view
return {
totalItems: totalItems,
currentPage: currentPage,
pageSize: pageSize,
totalPages: totalPages,
startPage: startPage,
endPage: endPage,
startIndex: startIndex,
endIndex: endIndex,
pages: pages
};
}
}
Below solution quite simple.
<pagination
total-items="totalItems"
items-per-page= "itemsPerPage"
ng-model="currentPage"
class="pagination-sm">
</pagination>
<tr ng-repeat="country in countries.slice((currentPage -1) * itemsPerPage, currentPage * itemsPerPage) ">
Here is sample jsfiddle
I've extracted the relevant bits here. This is a 'no frills' tabular pager, so sorting or filtering is not included. Feel free to change/add as needed:
//your data source may be different. the following line is
//just for demonstration purposes only
var modelData = [{
text: 'Test1'
}, {
text: 'Test2'
}, {
text: 'Test3'
}];
(function(util) {
util.PAGE_SIZE = 10;
util.range = function(start, end) {
var rng = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++)
rng.push(i);
return rng;
};
util.Pager = function(data) {
var self = this,
_size = util.PAGE_SIZE;;
self.current = 0;
self.content = function(index) {
var start = index * self.size,
end = (index * self.size + self.size) > data.length ? data.length : (index * self.size + self.size);
return data.slice(start, end);
};
self.next = function() {
if (!self.canPage('Next')) return;
self.current++;
};
self.prev = function() {
if (!self.canPage('Prev')) return;
self.current--;
};
self.canPage = function(dir) {
if (dir === 'Next') return self.current < self.count - 1;
if (dir === 'Prev') return self.current > 0;
return false;
};
self.list = function() {
var start, end;
start = self.current < 5 ? 0 : self.current - 5;
end = self.count - self.current < 5 ? self.count : self.current + 5;
return Util.range(start, end);
};
Object.defineProperty(self, 'size', {
configurable: false,
enumerable: false,
get: function() {
return _size;
},
set: function(val) {
_size = val || _size;
}
});
Object.defineProperty(self, 'count', {
configurable: false,
enumerable: false,
get: function() {
return Math.ceil(data.length / self.size);
}
});
};
})(window.Util = window.Util || {});
(function(ns) {
ns.SampleController = function($scope, $window) {
$scope.ModelData = modelData;
//instantiate pager with array (i.e. our model)
$scope.pages = new $window.Util.Pager($scope.ModelData);
};
})(window.Controllers = window.Controllers || {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table ng-controller="Controllers.SampleController">
<thead>
<tr>
<th>
Col1
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in pages.content(pages.current)" title="{{item.text}}">
<td ng-bind-template="{{item.text}}"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="4">
«
{{n + 1}}
»
</td>
</tr>
</tfoot>
</table>
The jQuery Mobile angular adapter has a paging filter you could base off of.
Here's a demo fiddle that uses it (add more than 5 items and it becomes paged): http://jsfiddle.net/tigbro/Du2DY/
Here's the source: https://github.com/tigbro/jquery-mobile-angular-adapter/blob/master/src/main/webapp/utils/paging.js
For anyone who find it difficult like me to create a paginator for a table I post this.
So, in your view :
<pagination total-items="total" items-per-page="itemPerPage" ng-model="currentPage" ng-change="pageChanged()"></pagination>
<!-- To specify your choice of items Per Pages-->
<div class="btn-group">
<label class="btn btn-primary" ng-model="radioModel" btn-radio="'Left'" data-ng-click="setItems(5)">5</label>
<label class="btn btn-primary" ng-model="radioModel" btn-radio="'Middle'" data-ng-click="setItems(10)">10</label>
<label class="btn btn-primary" ng-model="radioModel" btn-radio="'Right'" data-ng-click="setItems(15)">15</label>
</div>
//And don't forget in your table:
<tr data-ng-repeat="p in profiles | offset: (currentPage-1)*itemPerPage | limitTo: itemPerPage" >
In your angularJs:
var module = angular.module('myapp',['ui.bootstrap','dialogs']);
module.controller('myController',function($scope,$http){
$scope.total = $scope.mylist.length;
$scope.currentPage = 1;
$scope.itemPerPage = 2;
$scope.start = 0;
$scope.setItems = function(n){
$scope.itemPerPage = n;
};
// In case you can replace ($scope.currentPage - 1) * $scope.itemPerPage in <tr> by "start"
$scope.pageChanged = function() {
$scope.start = ($scope.currentPage - 1) * $scope.itemPerPage;
};
});
//and our filter
module.filter('offset', function() {
return function(input, start) {
start = parseInt(start, 10);
return input.slice(start);
};
});
I use this 3rd party pagination library and it works well. It can do local/remote datasources and it's very configurable.
https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination
<dir-pagination-controls
[max-size=""]
[direction-links=""]
[boundary-links=""]
[on-page-change=""]
[pagination-id=""]
[template-url=""]
[auto-hide=""]>
</dir-pagination-controls>
Since Angular 1.4, the limitTo filter also accepts a second optional argument begin
From the docs:
{{ limitTo_expression | limitTo : limit : begin}}
begin
(optional)
string|number
Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0.
So you don't need to create a new directive, This argument can be used to set the offset of the pagination
ng-repeat="item in vm.items| limitTo: vm.itemsPerPage: (vm.currentPage-1)*vm.itemsPerPage"
You can easily do this using Bootstrap UI directive.
This answer is a modification of the answer given by #Scotty.NET, I have changed the code because <pagination> directive is deprecated now.
Following code generates the pagination:
<ul uib-pagination
boundary-links="true"
total-items="totalItems"
items-per-page="itemsPerPage"
ng-model="currentPage"
ng-change="pageChanged()"
class="pagination"
previous-text="‹"
next-text="›"
first-text="«"
last-text="»">
</ul>
To make it functional, use this in your controller:
$scope.filteredData = []
$scope.totalItems = $scope.data.length;
$scope.currentPage = 1;
$scope.itemsPerPage = 5;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
, end = begin + $scope.itemsPerPage;
$scope.filteredData = $scope.data.slice(begin, end);
};
$scope.pageChanged();
Refer to this for more options of pagination: Bootstrap UI Pagination Directive
ng-repeat pagination
<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>
<script>
var app=angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', '$filter', function ($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.data = [];
$scope.q = '';
$scope.getData = function () {
return $filter('filter')($scope.data, $scope.q)
}
$scope.numberOfPages=function(){
return Math.ceil($scope.getData().length/$scope.pageSize);
}
for (var i=0; i<65; i++) {
$scope.data.push("Item "+i);
}
}]);
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
</script>
Previous messages recommended basically how to build a paging by yourself. If you are like me, and prefer a finished directive, I just found a great one called ngTable. It supports sorting, filtering and pagination.
It is a very clean solution, all you need in your view:
<table ng-table="tableParams" class="table">
<tr ng-repeat="user in $data">
<td data-title="'Name'" sortable="'name'">
{{user.name}}
</td>
<td data-title="'Age'" sortable="'age'">
{{user.age}}
</td>
</tr>
</table>
And in controller:
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: data.length, // length of data
getData: function($defer, params) {
// use build-in angular filter
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) :
data;
var start = (params.page() - 1) * params.count();
var end = params.page() * params.count();
$defer.resolve(orderedData.slice( start, end));
}
});
Link to GitHub: https://github.com/esvit/ng-table/
Angular-Paging
is a wonderful choice
A directive to aid in paging large datasets while requiring the bare minimum of actual paging information. We are very dependant on the server for "filtering" results in this paging scheme. The central idea being we only want to hold the active "page" of items - rather than holding the entire list of items in memory and paging on the client-side.
Old question but since I think my approach is a bit different and less complex I will share this and hope that someone besides me find it useful.
What I found to be an easy and small solution to pagination is to combine a directive with a filter which uses the same scope variables.
To implement this you add the filter on the array and add the directiv like this
<div class="row">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items | cust_pagination:p_Size:p_Step">
<td>{{item.Name}}</td>
<td>{{item.Price}}</td>
<td>{{item.Quantity}}</td>
</tr>
</tbody>
</table>
<div cust-pagination p-items="items" p-boundarylinks="true" p-size="p_Size" p-step="p_Step"></div>
</div>
p_Size and p_Step are scope variables which can be customized in the scope else the default value of the p_Size is 5 and p_Step is 1.
When a step is change in the pagination the p_Step is updated and will trigger a new filtering by cust_pagination filter.
The cust_pagination filter then slices the array depending on the p_Step value like below and only return the active records selected in the pagination section
var startIndex = nStep * nPageSize;
var endIndex = startIndex + nPageSize;
var arr = items.slice(startIndex, endIndex);
return arr;
DEMO View the complete solution in this plunker
There is my example. Selected button in the middle on the list
Controller.
config >>>
$scope.pagination = {total: null, pages: [], config: {count: 10, page: 1, size: 7}};
Logic for pagination:
/*
Pagination
*/
$scope.$watch('pagination.total', function (total) {
if(!total || total <= $scope.pagination.config.count) return;
_setPaginationPages(total);
});
function _setPaginationPages(total) {
var totalPages = Math.ceil(total / $scope.pagination.config.count);
var pages = [];
var start = $scope.pagination.config.page - Math.floor($scope.pagination.config.size/2);
var finish = null;
if((start + $scope.pagination.config.size - 1) > totalPages){
start = totalPages - $scope.pagination.config.size;
}
if(start <= 0) {
start = 1;
}
finish = start + $scope.pagination.config.size - 1;
if(finish > totalPages){
finish = totalPages;
}
for (var i = start; i <= finish; i++) {
pages.push(i);
}
$scope.pagination.pages = pages;
}
$scope.$watch("pagination.config.page", function(page){
_setPaginationPages($scope.pagination.total);
_getRespondents($scope.pagination.config);
});
and my view on bootstap
<ul ng-class="{hidden: pagination.total == 0}" class="pagination">
<li ng-click="pagination.config.page = pagination.config.page - 1"
ng-class="{disabled: pagination.config.page == 1}" >«</li>
<li ng-repeat="p in pagination.pages"
ng-click="pagination.config.page = p"
ng-class="{active: p == pagination.config.page}">{{p}}</li>
<li ng-click="pagination.config.page = pagination.config.page + 1"
ng-class="{disabled: pagination.config.page == pagination.pages.length}">»</li>
</ul >
It is useful
I wish I could comment, but I'll just have to leave this here:
Scotty.NET's answer and user2176745's redo for later versions are both great, but they both miss something that my version of AngularJS (v1.3.15) breaks on:
i is not defined in $scope.makeTodos.
As such, replacing with this function fixes it for more recent angular versions.
$scope.makeTodos = function() {
var i;
$scope.todos = [];
for (i=1;i<=1000;i++) {
$scope.todos.push({ text:'todo '+i, done:false});
}
};
Overview : Pagination using
- ng-repeat
- uib-pagination
View :
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead style="background-color: #eee">
<tr>
<td>Dispature</td>
<td>Service</td>
<td>Host</td>
<td>Value</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in app.metricsList">
<td>{{x.dispature}}</td>
<td>{{x.service}}</td>
<td>{{x.host}}</td>
<td>{{x.value}}</td>
</tr>
</tbody>
</table>
<div align="center">
<uib-pagination items-per-page="app.itemPerPage" num-pages="numPages"
total-items="app.totalItems" boundary-link-numbers="true"
ng-model="app.currentPage" rotate="false" max-size="app.maxSize"
class="pagination-sm" boundary-links="true"
ng-click="app.getPagableRecords()"></uib-pagination>
<div style="float: right; margin: 15px">
<pre>Page: {{app.currentPage}} / {{numPages}}</pre>
</div>
</div>
</div>
</div>
JS Controller :
app.controller('AllEntryCtrl',['$scope','$http','$timeout','$rootScope', function($scope,$http,$timeout,$rootScope){
var app = this;
app.currentPage = 1;
app.maxSize = 5;
app.itemPerPage = 5;
app.totalItems = 0;
app.countRecords = function() {
$http.get("countRecord")
.success(function(data,status,headers,config){
app.totalItems = data;
})
.error(function(data,status,header,config){
console.log(data);
});
};
app.getPagableRecords = function() {
var param = {
page : app.currentPage,
size : app.itemPerPage
};
$http.get("allRecordPagination",{params : param})
.success(function(data,status,headers,config){
app.metricsList = data.content;
})
.error(function(data,status,header,config){
console.log(data);
});
};
app.countRecords();
app.getPagableRecords();
}]);
I would like to add my solution that works with ngRepeat and filters that you use with it without using a $watch or a sliced array.
Your filter results will be paginated!
var app = angular.module('app', ['ui.bootstrap']);
app.controller('myController', ['$scope', function($scope){
$scope.list= ['a', 'b', 'c', 'd', 'e'];
$scope.pagination = {
currentPage: 1,
numPerPage: 5,
totalItems: 0
};
$scope.searchFilter = function(item) {
//Your filter results will be paginated!
//The pagination will work even with other filters involved
//The total number of items in the result of your filter is accounted for
};
$scope.paginationFilter = function(item, index) {
//Every time the filter is used it restarts the totalItems
if(index === 0)
$scope.pagination.totalItems = 0;
//This holds the totalItems after the filters are applied
$scope.pagination.totalItems++;
if(
index >= (($scope.pagination.currentPage - 1) * $scope.pagination.numPerPage)
&& index < ((($scope.pagination.currentPage - 1) * $scope.pagination.numPerPage) + $scope.pagination.numPerPage)
)
return true; //return true if item index is on the currentPage
return false;
};
}]);
In the HTML make sure that you apply your filters to the ngRepeat before the pagination filter.
<table data-ng-controller="myController">
<tr data-ng-repeat="item in list | filter: searchFilter | filter: paginationFilter track by $index">
<td>
{{item}}
</td>
<tr>
</table>
<ul class="pagination-sm"
uib-pagination
data-boundary-links="true"
data-total-items="pagination.totalItems"
data-items-per-page="pagination.numPerPage"
data-ng-model="pagination.currentPage"
data-previous-text="‹"
data-next-text="›"
data-first-text="«"
data-last-text="»">
</ul>
This below code will help for providing custom paging in backend with angular repeat.
Your data will be in
$scope.myticketIssuesData = [];
$scope.allticketIssuesData = [];
var jiraapp = angular.module('jiraapp', ['ui.bootstrap']);
jiraapp.controller('JiraController', ['$scope', '$http', '$window','$location', function JiraController($scope, $http, $window,$location) {
$scope.myticketIssuesData = [];
$scope.allticketIssuesData = [];
$scope.jiraIssue = {};
$scope.RequesterType = [];
$scope.loading = false;
$scope.showerror = false;
$scope.alert = {};
$scope.maxSize = 10;
$scope.totalCount = 0;
$scope.pageIndex = 0;
$scope.startIndex = 0;
$scope.pageSizeSelected = 10;
$scope.maxallSize = 10;
$scope.totalallCount = 0;
$scope.pageallIndex = 0;
$scope.startallIndex = 0;
$scope.pageallSizeSelected = 10;
$scope.getUserTickets = function() {
$scope.loading = true;
$http({
method: 'GET',
url: 'http://localhost:53583/api/Jira/getUserTickets?assignee='+$scope.loc+'&startAt='+ $scope.startIndex +'&maxResults='+$scope.pageSizeSelected,
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080",
"crossDomain": "true",
}
}).then(function successCallback(response) {
$scope.myticketIssuesData = response.data.issues;
$scope.totalCount = response.data.total;
$scope.loading = false;
}, function errorCallback(response) {
$scope.loading = false;
});
}
$scope.getrequestType = function(){
$http({
method: 'GET',
url: 'http://localhost:53583/api/Jira/getrequestType',
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080",
"crossDomain": "true",
}
}).then(function successCallback(response) {
$scope.RequesterType = response.data.values;
}, function errorCallback(response) {
});
}
$scope.getDropDown = function(){
$scope.getrequestType();
}
$scope.initialize = function (item) {
$scope.getUserTickets();
$scope.getDropDown();
}
$scope.initialize();
$scope.pageChanged = function () {
if($scope.pageIndex == 0)
$scope.startIndex = 0;
else if($scope.pageIndex == 1)
$scope.startIndex = 0;
else
$scope.startIndex = (($scope.pageIndex-1) * $scope.pageSizeSelected);
$scope.getUserTickets();
};
$scope.pageallChanged = function () {
if($scope.pageallIndex == 0)
$scope.startallIndex = 0;
else if($scope.pageallIndex == 1)
$scope.startallIndex = 0;
else
$scope.startallIndex = (($scope.pageallIndex-1) * $scope.pageallSizeSelected);
$scope.getAllTickets();
};
$scope.changeallPageSize = function () {
$scope.pageallIndex = 0;
$scope.getAllTickets();
};
$scope.getAllTickets = function() {
$scope.loading = true;
$http({
method: 'GET',
url: 'http://localhost:53583/api/Jira/getAllTickets?startAt='+ $scope.startallIndex +'&maxResults='+$scope.pageallSizeSelected,
headers: {
"Accept": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080",
"crossDomain": "true",
}
}).then(function successCallback(response) {
$scope.allticketIssuesData = response.data.issues;
$scope.totalallCount = response.data.total;
$scope.loading = false;
}, function errorCallback(response) {
$scope.loading = false;
});
}
}]);
<html ng-app="jiraapp">
<head>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous">
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro' rel='stylesheet' type='text/css'>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
crossorigin="anonymous"></script>
<script src="/angular.min.js"></script>
<script src="/jira.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-route.min.js"></script>
<script src="/ui-bootstrap-tpls-0.13.4.min.js"></script>
<!-- this is important -->
<style type="text/css">
#loading {
position: fixed;
top: 50%;
left: 50%;
margin-top: -5em;
margin-left: -10em;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px
}
.pagination>li {
display: inline
}
.pagination>li>a,
.pagination>li>span {
position: relative;
float: left;
padding: 6px 12px;
margin-left: -1px;
line-height: 1.42857143;
color: #337ab7;
text-decoration: none;
background-color: #fff;
border: 1px solid #ddd
}
.pagination>li:first-child>a,
.pagination>li:first-child>span {
margin-left: 0;
border-top-left-radius: 4px;
border-bottom-left-radius: 4px
}
.pagination>li:last-child>a,
.pagination>li:last-child>span {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px
}
.pagination>li>a:focus,
.pagination>li>a:hover,
.pagination>li>span:focus,
.pagination>li>span:hover {
z-index: 3;
color: #23527c;
background-color: #eee;
border-color: #ddd
}
.pagination>.active>a,
.pagination>.active>a:focus,
.pagination>.active>a:hover,
.pagination>.active>span,
.pagination>.active>span:focus,
.pagination>.active>span:hover {
z-index: 2;
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7
}
.pagination>.disabled>a,
.pagination>.disabled>a:focus,
.pagination>.disabled>a:hover,
.pagination>.disabled>span,
.pagination>.disabled>span:focus,
.pagination>.disabled>span:hover {
color: #777;
cursor: not-allowed;
background-color: #fff;
border-color: #ddd
}
.pagination-lg>li>a,
.pagination-lg>li>span {
padding: 10px 16px;
font-size: 18px;
line-height: 1.3333333
}
.pagination-lg>li:first-child>a,
.pagination-lg>li:first-child>span {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px
}
.pagination-lg>li:last-child>a,
.pagination-lg>li:last-child>span {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px
}
.pagination-sm>li>a,
.pagination-sm>li>span {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5
}
.pagination-sm>li:first-child>a,
.pagination-sm>li:first-child>span {
border-top-left-radius: 3px;
border-bottom-left-radius: 3px
}
.pagination-sm>li:last-child>a,
.pagination-sm>li:last-child>span {
border-top-right-radius: 3px;
border-bottom-right-radius: 3px
}
.pager {
padding-left: 0;
margin: 20px 0;
text-align: center;
list-style: none
}
.pager li {
display: inline
}
.pager li>a,
.pager li>span {
display: inline-block;
padding: 5px 14px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 15px
}
.pager li>a:focus,
.pager li>a:hover {
text-decoration: none;
background-color: #eee
}
.pager .next>a,
.pager .next>span {
float: right
}
.pager .previous>a,
.pager .previous>span {
float: left
}
.pager .disabled>a,
.pager .disabled>a:focus,
.pager .disabled>a:hover,
.pager .disabled>span {
color: #777;
cursor: not-allowed;
background-color: #fff
}
</style>
</head>
<body ng-controller="JiraController">
<div class="col-sm-12">
<div class="row" style="background: #09c;">
<div style="margin-left: auto; margin-right: auto;">
<img src="/logo.png" height="80">
<span class="d-none d-sm-inline"
style="color: white; font-size: 4rem; vertical-align: middle; font-family:'Source Code Pro'">Jira</span>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<nav>
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<a class="nav-item nav-link active" id="nav-myticket-tab" data-toggle="tab" href="#nav-myticket"
role="tab" aria-controls="nav-myticket" aria-selected="true" ng-click="getUserTickets()">My
Ticket</a>
</div>
</nav>
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-myticket" role="tabpanel"
aria-labelledby="nav-myticket-tab">
<div class="col-sm-12" style="margin:10px">
<div id="loading" ng-show="loading">
<img src="spinner.gif">
</div>
<table ng-show="!loading" class="table table-striped table-bordered table-hover tabel-condensed">
<thead>
<tr>
<td>Key</td>
<td>Priority</td>
<td>Summary</td>
<td>Assignee</td>
<td>Status</td>
<td>Due Date</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in myticketIssuesData">
<td>
<a href={{data.fields.customfield_10023._links.web}} target="_blank">
{{data.key}}
</a>
</td>
<td>{{data.fields.priority.name}}</td>
<td>{{data.fields.summary}}</td>
<td>{{data.fields.assignee.displayName}}</td>
<td>{{data.fields.status.name}}</td>
<td>{{data.fields.duedate}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td align="center" colspan="6">
<!-- <span class="form-group pull-left page-size form-inline">
<select id="ddlPageSize" class="form-control control-color"
ng-model="pageSizeSelected" ng-change="changePageSize()">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</span> -->
<div class="pull-right">
<pagination total-items="totalCount" ng-change="pageChanged()"
items-per-page="pageSizeSelected" direction-links="true"
ng-model="pageIndex" max-size="maxSize" class="pagination"
boundary-links="true" rotate="false" num-pages="numPages">
</pagination>
<a style="margin-left: 640px;" class="btn btn-primary">Page: {{pageIndex}} / {{numPages}}</a>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Resources