pagination of my dataTable in angularJS - javascript

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/

Related

AngularJS pagination bug: can not capture current page index

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>

How to avoid flickering effect in angularjs

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.

Not able to push $log data to txt file

I have a local amp setup where I am trying to push angular $log messages to a txt file. But I keep getting a javaScript error. Here is the error
angular.js:9101 TypeError: $scope.todos.push is not a function
Here is my code:
angular.module('Todo', []).factory('myhttpserv', function($http) {
return $http.get('storage.txt').error(function(status) {
console.log(status)
});
}).controller('TodoController', function($scope, myhttpserv, $http) {
$scope.appTitle = "MyTodoList",
myhttpserv.then(function(response) {
$scope.todos = (response.data !== null) ? response.data : [];
var httpPost = function() {
$http.post('save.php', JSON.stringify($scope.todos)).error(function(status) {
console.log(status)
});
};
$scope.addTodo = function() {
$scope.todos.push({
text: $scope.todoText,
doneProd: false,
doneDev: false
});
$scope.todoText = ''; //clear the input after adding
httpPost();
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.doneProd && todo.doneDev ? 0 : 1;
});
return count;
};
$scope.archive = function() {
var rusure = confirm("Are you sure you want to remove the completed tasks from the list?");
if (rusure) {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.doneProd || !todo.doneDev)
$scope.todos.push(todo);
});
httpPost();
}
};
$scope.delete = function(idx) {
var rusure = confirm("Are you sure you want to remove the task from the list?");
if (rusure) {
$scope.todos.splice(idx, 1);
httpPost();
}
};
$scope.edit = function(idx) {
var changes = prompt("Please make the changes below", $scope.todos[idx].text);
if (changes != null) {
$scope.todos[idx].text = changes;
httpPost();
}
};
$scope.checkboxClick = function() {
httpPost();
};
$('.splash, .container').fadeToggle();
});
});
<div class="splash">
<h2>Loading</h2>
</div>
<div class="container">
<header class="app-header">
<h1 class="app-title" data-ng-bind="appTitle"></h1>
</header>
<section class="app-body">
<table>
<thead>
<tr>
<th>
TITLE
</th>
<th></th>
<th></th>
<th class="chk">
PROD
</th>
<th class="chk">
DEV
</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="todo in todos track by $index">
<td>
<span class="done-{{ todo.doneProd && todo.doneDev }}" data-ng-bind="todo.text"></span>
</td>
<td>
<a data-ng-click="delete($index)"><i class="fa fa-times"></i></a>
</td>
<td>
<a data-ng-click="edit($index)"><i class="fa fa-pencil-square-o"></i></a>
</td>
<td class="chk">
<input type="checkbox" data-ng-model="todo.doneProd" data-ng-change="checkboxClick()">
</td>
<td class="chk">
<input type="checkbox" data-ng-model="todo.doneDev" data-ng-change="checkboxClick()">
</td>
</tr>
</tbody>
</table>
<section class="archive-control">
<span>{{ remaining() }} of {{ todos.length }} remaining</span>
<a class="fr" href="" data-ng-click="archive()" data-ng-show="remaining() < todos.length">Remove Completed Items</a>
</section>
<form data-ng-submit="addTodo()" class="todo-form">
<input type="text" data-ng-model="todoText" placeholder="Enter new task item" />
<br />
<input type="submit" value="Add Task" />
</form>
</section>
</div>
here is my php file and I do have my storage.txt in the folder also:
<?php
$data = file_get_contents("php://input");
$myfile = fopen("log.txt", "w") or die("Unable to open file!");
fwrite($myfile, $data);
fclose($myfile);
?>

keep track of each $timeout when calling the same function multiple times

$scope.fetchStatus = function (job) {
$http
.get('http://gtrapi/pool/checkStatus/' + sessionId + '/' + job.jobId)
.success(function (response) {
job[job.jobId] = response;
if (response.status !== 'InProgress') {
$scope.refreshDataTimeout = $timeout($scope.fetchStatus(job), 1000);
}
})
.error (function () {
});
};
Here is my HTML code
<div ng-repeat="job in gtrLogs" class="each-log">
<div class="row job-id">
<div class="col-xs-2">
Job ID: {{job.jobId}}
</div>
<div class="col-xs-10">
End Point: {{job.changes.endpoint}}
</div>
</div>
<div class="each-job" ng-init="fetchStatus(job)">
<div class="job-header row">
<span class="col-xs-6">Job Status: <strong>{{job[job.jobId].status}}</strong>
<span class="glyphicon" ng-class="{'glyphicon-refresh spin' : job[job.jobId].status === 'InProgress', 'glyphicon-ok' : job[job.jobId].status === 'submitted', 'glyphicon-remove' : job[job.jobId].status === 'Aborted'}"></span>
</span>
<span class="col-xs-6">
<span class="glyphicon glyphicon-stop pull-right" ng-click="stopLogs()" tooltip="Stop Action"></span>
<span class="glyphicon glyphicon-repeat pull-right" ng-click="rollBack()" tooltip="Roll Back"></span>
</span>
</div>
<div class="logs-progress">
<table class="table table-striped table-condensed table-hover">
<thead>
<tr>
<th>
Message
</th>
<th>
Time
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in job[job.jobId].logs">
<td>{{row.msg}}</td>
<td>{{row.time | date:'yyyy/MM/dd HH:mm:ss'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I have to update the data every second and placed $timeout in the function. But because the function is being called multiple times from the HTML the calls are nested.
How Do I keep polling with respect to the same job.
Since you have a unique jobid, use can use that to maintain an array of key value pairs where your job id can correspond to a unique counter.
var counters = [];
$scope.fetchStatus = function (job) {
$http
.get('http://url:9090/gtrapi/pool/checkStatus/' + sessionId + '/' + job.jobId)
.success(function (response) {
job[job.jobId] = response;
if (response.status !== 'InProgress') {
updateCounter(job.jobId);
$scope.refreshDataTimeout = $timeout($scope.fetchStatus(job), 1000);
}
})
.error (function () {
});
};
function updateCounter(jobId) {
var exists = false,
jobId = parseInt(jobId);
for (var i in counters) {
if (counters[i].id === jobId) {
projects[i].counter++;
exists = true;
break;
}
}
if (!exists) {
counters.push({id: jobId, counter: 0});
}
}

Datatable in angularjs not working

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;
}

Categories