.replace() causing site to flicker - javascript

I am using mongoose-paginate-v2 on the backend to paginate the response from my DB. I am trying to setup the front end to move through the data and send a request for the new data as needed. (That part seems to be working). The problem I am having is the DOM seems to freak out after pressing the next / back buttons a few times. VIDEO of problem which is at the end of the 20sec vid: (https://drive.google.com/file/d/1btfeKqXELEMmBnFPpkCbBLY5uhrC1bvE/view?usp=sharing)
What I have tried: I have tried .emtpy, .remove, and now .replace all seem to have the same problem. I have also moved the code around to try and make it unti the prior .then() was complete. Here is the code:
Front End:
<% include ../partials/header%>
<div class="container-fluid pt-3">
<div class='row'>
<div class="col-md-1">
<button class="btn btn-outline-primary sticky-top">Start New Call</button>
</div>
<div class="col-md-11">
<table class="table">
<thead class="sticky-top">
<tr>
<th scope="col">Incident #</th>
<th scope="col">Type</th>
<th scope="col">Location</th>
<th scope="col">Units</th>
<th scope="col">Dispatch</th>
<th scope="col">Clear</th>
<th scope="col">Disposition</th>
<th scope="col">Recall</th>
</tr>
</thead>
<tbody id="callTable">
<tr id="row1"><td></td></tr>
<tr id="row2"><td></td></tr>
<tr id="row3"><td></td></tr>
<tr id="row4"><td></td></tr>
<tr id="row5"><td></td></tr>
<tr id="row6"><td></td></tr>
<tr id="row7"><td></td></tr>
<tr id="row8"><td></td></tr>
<tr id="row9"><td></td></tr>
<tr id="row10"><td></td></tr>
</tbody>
</table>
<div class="row">
<div class="col-3"></div>
<div class="text-center col-2">
<button id="back" class="btn btn-outline-success mr-auto"><i class="fas fa-step-backward"></i><strong>Back</strong></button>
</div>
<div class="justify-content-center d-flex col-2 align-items-center">
<strong>Page <span id="pgnum">##</span> of <span id="totalpgs">##</span></strong>
</div>
<div class="text-center col-2">
<button id="next" class="btn btn-outline-success ml-auto"><strong>Next</strong><i class="fas fa-step-forward"></i></button>
</div>
<div class="text-center col-3"></div>
</div>
</div>
</div>
</div>
<% include ../partials/footer %>
<script>
//Data Management Script
let list=[];
axios.get('/api/cnc/incidents')
.catch(err=>{
console.log(err);
})
.then(data=>{
return list=data;
})
//Setup Function to get data...
async function getPage(page){
axios.get('/api/cnc/incidents/'+page)
.catch(err=>{
console.log(err);
})
.then(response=>{
console.log(response);
calls = response.data.docs;
callNumber = 'Not Assigned';
next = response.data.hasNextPage,
back = response.data.hasPrevPage,
nextPage = response.data.nextPage,
prevPage = response.data.prevPage;
$('#pgnum').text(response.data.page);
$('#totalpgs').text(response.data.totalPages);
if(next === true){
$('#next').removeAttr('disabled');
$('#next').click(function () {
getPage(nextPage);
});
}else{
$('#next').attr('disabled', 'disabled');
}
if(back === true){
$('#back').removeAttr('disabled');
$('#back').click(function () {
getPage(prevPage);
});
}else{
$('#back').attr('disabled', 'disabled');
}
// activities.sort((a, b) => b.date - a.date)
calls.sort((a, b) => (a.times.dispatch > b.times.dispatch) ? -1 : 1)
return calls;
}).then(calls=>{
let i = 1;
calls.forEach(call => {
//Set default callNumber.
callNumber = 'Not Assigned'
//Update to call number from DB.
if(call.incidentNumber){
callNumber = call.incidentNumber;
}
//Change _id to Radio ID.
if(call.units.length > 0){
let assignedUnits = call.units;
let idArray = list.data[0];
const filtered = [];
function compare(assignedUnits,idArray){
assignedUnits.forEach((unit)=>{
idArray.forEach((unitId)=>{
if(unit === unitId._id){
filtered.push(unitId.id);
}
})
})
return filtered;
}
compare(assignedUnits, idArray);
callUnits = filtered.join(', ');
}else{
callUnits = ['None']
}
if(typeof call.disposition !== 'undefined'){
callDisposition = call.disposition.selected;
}else{
callDisposition = '';
}
if(call.times.clear === undefined){
callClear = '';
}else{
callClear = call.times.clear;
}
//Insert Data into DOM. and make TR the link to edit
$('#row'+i).replaceWith('<tr id="row'+i+'" onClick="editRun(\''+call._id+'\')"><th>'+callNumber+'</th><td>'+call.callType+'</td><td>'+call.address.placeName+' '+call.address.streetAddress+'</td><td>'+callUnits+'</td><td>'+call.times.dispatch+'</td><td>'+callClear+'</td><td>'+callDisposition+'</td><td id="recall">'+call.recall.length+' personnel</td></tr>');
i++;
});
})
}
//Get the first page of data...
getPage(1);
function editRun(runId){
window.location.href= '/api/cnc/incident/input/'+runId;
}
//Update Navbar correctly
$('document').ready(function(){
$('.top-nav').removeClass('active').addClass('text-light').removeClass('text-dark');
$('#incidentTab').addClass('active').addClass('text-dark').removeClass('text-light');
});
</script>

Related

How to dynamically update the components in ReactJS

I am new to React and I don't know how to overcome the below situation.
Let say I have to display a table.In Table <td> i have one dropdown which I got from my child component.And also have some <div> next to the dropdown.
So,for each dropdown change, i have to bind some html into that <div>.Below line is working for very first dropdown change.
ReactDOM.render(myHtml, document.getElementById(myID));
So For a second time it is not render the new html.
Kindly correct me If I did anything wrong and give me some suggestion to overcome the above issue.
Thanks in Advance.
class Home extends Component{
state = {
tableDetails:'',
};
LoadTableDetails = () => {
const getUrl = "Some API Url";
let dd= fetch(getUrl);
dd.then(response => {
return response.json();
}).then(items => {
var body = this.getTableBody(items);
this.setTableDetails(body);
});
}
getTableBody(items){
let body ;
if(items != null){
body = items.map((folder,index) =>
<tr key={index}>
<td>{folder.FolderName}</td>
<td>
<MyDropDown fileNames={folder.FileNames} folderFiles={folder.FolderFiles} id={folder.FolderName.replace(/ /g,'_')} setSelectedFile = {this.setSelectedFile}/> // Here I get dropdown selected value and see setSelectedFile method
</td>
<td>
<div id={folder.FolderName.replace(/ /g,'_')}>
////I need some html here based on the above dropdown change
</div>
</td>
<td></td>
</tr>
);
}
return folderItems;
}
setTableDetails(body){
let dd = (<div className="container" >
<h2 class="text-center">Server Details</h2>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Folder</th>
<th scope="col">Config Files</th>
<th scope="col">Config Section</th>
<th scope="col">App Settings</th>
</tr>
</thead>
<tbody>
{body}
</tbody>
</table>
</div>);
this.setState({tableDetails:dd});
}
setSelectedFile = (val) =>{
const getUrl = 'my url';
let loadItems = fetch(getUrl);
loadItems.then(response=>{
return response.json();
}).then(data=>{
let configHtml = (
<div>
<MyDropDown fileNames={data} id={val.id + path.replace('\\','_').replace('/\//g','_')} path={path} setSelectedFile = {this.getConfigSectionDetails}/>
<div className="mt-4" id={val.id + path.replace('\\','_').replace('/\//g','_')}>
</div>
</div>
);
let id = val.id; //This is the id where my new
ReactDOM.render(configHtml, document.getElementById(id)); //this line is working for my first dropdown change.If I change the dropdown again then it is not rerenered
});
}
render(){
return (
<div class="mt-4">
<div class="input-group-append">
<button class="btn btn-info" type="button" onClick={this.LoadTableDetails}>Load Table Details</button>
</div>
{this.state.tableDetails}
</div>
);
}
}
export default Home;
I got my Answer.We have to use our states to update the values and not html.
class Home extends Component{
state = {
tableDetails:'',
dropdownDetails:''
};
LoadTableDetails = () => {
const getUrl = "Some API Url";
let dd= fetch(getUrl);
dd.then(response => {
return response.json();
}).then(items => {
this.setState({
tableDetails:items
});
});
}
getTableDetails = (items)=>{
return (<div className="container" >
<h2 class="text-center">Server Details</h2>
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">Folder</th>
<th scope="col">Config Files</th>
<th scope="col">Config Section</th>
<th scope="col">App Settings</th>
</tr>
</thead>
<tbody>
{
items.map((folder,index) =>{
return (<tr key={index}>
<td>{folder.FolderName}</td>
<td>
<MyDropDown fileNames={folder.FileNames} folderFiles={folder.FolderFiles} id=index setSelectedFile ={this.setSelectedFile}/>
</td>
<td>
<div>
{this.getConfigHtml(this.state.dropdownDetails)}
</div>
</td>
<td></td>
</tr>)
})
}
</tbody>
</table>
</div>);
}
getConfigHtml =(val)=>{
return (
<div>
<MyDropDown fileNames={val.data} path={val.path} setSelectedFile = {this.getConfigSectionDetails}/>
</div>
);
}
setSelectedFile = (val) =>{
const getUrl = 'my url';
let loadItems = fetch(getUrl);
loadItems.then(response=>{
return response.json();
}).then(data=>{
let val={
data:data,
path:val.path
};
this.setState({dropdownDetails:val});
});
}
render(){
return (
<div class="mt-4">
<div class="input-group-append">
<button class="btn btn-info" type="button" onClick={this.LoadTableDetails}>Load Table Details</button>
</div>
{this.getTableDetails(this.state.tableDetails)}
</div>
);
}
}
export default Home;

Automatic scroll not working on click in angularJS

I have to scroll in a particular block(in may case table) when I will click on button.
vm.uploadOmrFile = function() {
vm.formSubmitted = true;
if (!vm.partners) {
return;
} else if (!vm.omrConfigurations) {
return;
} else if (!vm.schools) {
return;
} else if (!vm.classes) {
return;
}
formdata.append('classId', vm.configuration.classId);
// formdata.append('omrConfigId', vm.configuration.omrConfigId);
formdata.append('schoolId', vm.configuration.schoolId);
// formdata.append('tenantId', vm.configuration.tenantId);
var request = {
method: 'POST',
url: xxxxxx,
data: formdata,
transformRequest : angular.identity,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
$http(request)
.success(function (d) {
vm.badrecords = 0;
vm.uploadresponse = d;
vm.records = d.studentAssessments;
vm.records.forEach(function(record){
if(record.output.type == 'invalid-csv') {
vm.badrecords += 1;
}
})
})
.error(function (error) {
toastr(error);
});
setTimeout(function() {
// set the location.hash to the id of
// the element you wish to scroll to.
$location.path('/omr-upload');
$location.hash('message');
$anchorScroll();
}, 20000);
}
This is html file
<!doctype html>
<html>
<div class="modal-footer">
<button ng-click="vm.uploadOmrFile()" formnovalidate
class="btn btn-success" value="Upload"
dismiss="modal">Upload</button>
<button type="button" class="btn btn-danger" data-
dismiss="modal">Cancel</button>
</div>
<tr>
<td class="nopadding noborder">
<table class="table">
<tr>
<td colspan="4">
<div class="alert alert-danger" id="message" ng-
if="vm.uploadresponse vm.uploadresponse.hasError"
role="alert">{{vm.uploadresponse.hasError}}
<strong>{{vm.uploadresponse.message}}</strong>
<br> Total Records Parsed:{{vm.records.length}}
<br>RecordsError: {{vm.badrecords}}
</div>
<div class="alert alert-success" id="message" ng-
if="vm.uploadresponse && !vm.uploadresponse.hasError">
<strong>{{vm.uploadresponse.message}}</strong>
<br> Total Records Parsed : {{vm.records.length}}
<br>Records with Error: 0
</div>
</td>
</tr>
<tr ng-if="vm.uploadresponse &&
vm.uploadresponse.hasError">
<th>Name</th>
<th>Sheet ID</th>
<th>Record Type</th>
<th>Messages</th>
</tr>
<tr ng-repeat="record in vm.records" ng-
if="vm.uploadresponse && vm.uploadresponse.hasError">
<td>{{record.name}}</td>
<td>{{record.omrsheet}}</td>
<td>{{record.output.type}}</td>
<td>
<div style="height:100px;overflow-y:scroll">
<div ng-repeat="msg in record.output.messages"
class="error">
<p>{{msg}}</p>
</div>
</div>
</td>
</tr>
<tr ng-if="vm.uploadresponse &&
!vm.uploadresponse.hasError">
<td>
<h2><i class="glyphicon glyphicon-thumbs-up" aria-
hidden="true"></i> All records fine!
<button class="btn btn-warning btn-lg" ng-
click="vm.saveOMR()">Click to Save OMR
data</button>
</h2>
</td>
</tr>
</table>
</td>
</tr>
</html>
My problem is when i Click to upload button It should go table section of html and upload button calling "uploadOmrFile()".
In my case scroll not going to table section.
I am using id as "message", which is uses location.hash.
setTimeout(function()
{
document.getElementById('message').scrollIntoView({block: 'start',
behavior: 'smooth'}); },1000);`
Paste This code After getting response

Adding javascript code on laravel html page

I am trying to add a Pay Now button to a html page on laravel, below is code on a controller file PaymentsController.php
function invoice($id){
$return = array();
$return['payment'] = payments::where('id',$id)->first()->toArray();
$return['siteTitle'] = $this->panelInit->settingsArray['siteTitle'];
$return['baseUrl'] = URL::to('/');
$return['address'] = $this->panelInit->settingsArray['address'];
$return['address2'] = $this->panelInit->settingsArray['address2'];
$return['systemEmail'] = $this->panelInit->settingsArray['systemEmail'];
$return['phoneNo'] = $this->panelInit->settingsArray['phoneNo'];
$return['paypalPayment'] = $this->panelInit->settingsArray['paypalPayment'];
$return['currency_code'] = $this->panelInit->settingsArray['currency_code'];
$return['currency_symbol'] = $this->panelInit->settingsArray['currency_symbol'];
$return['paymentTax'] = $this->panelInit->settingsArray['paymentTax'];
$return['amountTax'] = ($this->panelInit->settingsArray['paymentTax']*$return['payment']['paymentAmount']) /100;
$return['totalWithTax'] = $return['payment']['paymentAmount'] + $return['amountTax'];
$return['user'] = User::where('id',$return['payment']['paymentStudent'])->first()->toArray();
return $return;
}
Below is the invoice html page where I want to add the Pay Now button
<div class="row invoice-info">
<div class="col-sm-4 invoice-col">
{{phrase.from}}
<address>
<strong>{{invoice.siteTitle}}</strong><br>
{{invoice.address}}<br>
{{invoice.address2}}<br>
{{phrase.phoneNo}}: {{invoice.phoneNo}}<br/>
{{phrase.email}}: {{invoice.systemEmail}}
</address>
</div>
<div class="col-sm-4 invoice-col">
{{phrase.tp}}
<address>
<strong>{{invoice.user.fullName}}</strong><br>
{{invoice.user.address}}<br>
{{phrase.phoneNo}}: {{invoice.user.phoneNo}}<br/>
{{phrase.email}}: {{invoice.user.email}}
</address>
</div>
<div class="row">
<div class="col-xs-12 table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>{{phrase.Product}}</th>
<th>{{phrase.Description}}</th>
<th>{{phrase.Subtotal}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{invoice.payment.paymentTitle}}</td>
<td>{{invoice.payment.paymentDescription}}</td>
<td>{{invoice.currency_symbol}} {{invoice.payment.paymentAmount}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<!-- accepted payments column -->
<div class="col-xs-6"></div>
<div class="col-xs-6">
<p class="lead"><br/>{{phrase.AmountDue}} {{invoice.payment.paymentDate * 1000 | date:$root.angDateFormat}}</p>
<div class="table-responsive">
<table class="table">
<tr>
<th style="width:50%">{{phrase.Subtotal}}:</th>
<td>{{invoice.currency_symbol}} {{invoice.payment.paymentAmount}}</td>
</tr>
<tr>
<th>{{phrase.payTax}} ({{invoice.paymentTax}}%)</th>
<td>{{invoice.currency_symbol}} {{invoice.amountTax}}</td>
</tr>
<tr>
<th>{{phrase.Total}}:</th>
<td>{{invoice.currency_symbol}} {{invoice.totalWithTax}}</td>
</tr>
</table>
</div>
</div>
</div>
Below is the pay now button and a sample javascript code that I will be adding to the invoice page
<script src="https://js.paytest.co/v1/inline.js"></script>
Pay Via Card
</div>
</div>
<script>
function payWithPaytest(){
var handler = PaytestPop.setup({
key: 'PublicKey',
email: 'customer#email.com',
amount: 1000,
ref: "",
callback: function(response){
window.location = "";
},
onClose: function(){
alert('window closed');
}
});
handler.openIframe();
}
</script>
My issue here is how do I declare this value "{{invoice.totalWithTax}}" as the amount in the javascript code. When I try to add it using the code below, it doesn't work.
<script>
function payWithPaytest(){
var handler = PaytestPop.setup({
key: 'PublicKey',
email: 'customer#email.com',
amount: {{invoice.totalWithTax}},
ref: "",
callback: function(response){
window.location = "";
},
onClose: function(){
alert('window closed');
}
});
handler.openIframe();
}
</script>

AngularJS - Pagination Example with Logic like Google

I have tried to implement this paging solution that I found online from this link:
http://jasonwatmore.com/post/2016/01/31/AngularJS-Pagination-Example-with-Logic-like-Google.aspx
I think the issue is in the way the functions are called, because the setPage function gets called before I have all my data so it does not know how many total items there are to be displayed etc. Can someone take a quick look and see what I'm doing wrong?
function HistoryController($window, $scope, $modal, $state, toaster, PagerService, HistoryFactory, $timeout) {
var vm = this;
vm.uploads = [];
vm.includeCancelled = false;
vm.uploadDataModal = {};
vm.pager = {};
vm.setPage = setPage;
activate();
function activate() {
getHistory();
vm.setPage(1);
}
function setPage(page) {
if (page < 1 || page > vm.pager.totalPages) {
return;
}
// get pager object from service
vm.pager = PagerService.GetPager(vm.uploads.length, page);
// get current page of items
vm.items = vm.uploads.slice(vm.pager.startIndex, vm.pager.endIndex + 1);
}
function getHistory() {
HistoryFactory.getHistory(vm.includeCancelled).then(
function(response) {
_.each(response.data, function(upload) {
upload.inProgress = upload.status && ['INPROGRESS','NEW'].indexOf(upload.status.statusCd.trim()) > -1;
});
vm.uploads = response.data;
if($state.params.reupload){
uploadProductionData();
$state.params.reupload = false;
}
});
}
Here is the html
<div class="chrthdr" ui-view="header"></div>
<div id="userResults">
<div class="card card-full-width">
<div class="card-header dark-blue">
<a class="card-config" data-toggle="uploadHistory" data-placement="left"><i class="glyphicon glyphicon-info-sign"></i></a>
<div class="card-title">Data History</div>
</div>
<div class='form-horizontal range-date' style="overflow-y: auto;">
<form>
<div class="panel-body">
<div>
<span class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; margin-right: 5px" type="button" ng-click="vm.uploadProductionData()">Upload Data</span>
<label>
<input type="checkbox" ng-model="vm.includeCancelled">Include removed executions
</label>
<!--<span class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; margin-left: 5px" type="button" ng-click="vm.viewTemplates()">Download Template</span>-->
</div>
<div>
<table class="table">
<tr>
<th>Upload Date</th>
<th>Product</th>
<th>Comments</th>
<th>Template</th>
<th>Last Updated By</th>
<th>Last Updated</th>
<th>Status</th>
<th>Actions</th>
</tr>
<tr ng-repeat="upload in vm.uploads | orderBy:'uploadDate':true">
<td style="white-space: nowrap;">{{upload.uploadDate}}</td>
<td>{{upload.product}}</td>
<td style="white-space: nowrap;">{{upload.comments}}</td>
<td style="white-space: nowrap;">{{upload.templateName}}</td>
<td style="white-space: nowrap;">{{upload.lastUpdatedByUser}}</td>
<td style="white-space: nowrap;">{{upload.lastUpdateDate}}</td>
<td style="white-space: nowrap;">{{upload.status.statusName}}</td>
<td>
<button class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; " ng-hide="upload.status.statusCd === 'NEW' || upload.status.statusCd === 'ERROR'" ng-click="vm.loadStagingPage(upload.dataLoadExecutionId, upload.product, upload.status)">View</button>
<span class="btn btn-primary btn-xs pull-left" style="margin-bottom: 5px; " type="button" ng-click="vm.cancelDataExecution(upload.dataLoadExecutionId)" ng-show="upload.inProgress || upload.status.statusCd === 'ERROR'">Remove</span>
</td>
</tr>
</table>
</div>
<div class="text-center">
<ul ng-if="vm.pager.pages.length" class="pagination">
<li ng-class="{disabled:vm.pager.currentPage === 1}">
<a ng-click="vm.setPage(1)">First</a>
</li>
<li ng-class="{disabled:vm.pager.currentPage === 1}">
<a ng-click="vm.setPage(vm.pager.currentPage - 1)">Previous</a>
</li>
<li ng-repeat="page in vm.pager.pages" ng-class="{active:vm.pager.currentPage === page}">
<a ng-click="vm.setPage(page)">{{page}}</a>
</li>
<li ng-class="{disabled:vm.pager.currentPage === vm.pager.totalPages}">
<a ng-click="vm.setPage(vm.pager.currentPage + 1)">Next</a>
</li>
<li ng-class="{disabled:vm.pager.currentPage === vm.pager.totalPages}">
<a ng-click="vm.setPage(vm.pager.totalPages)">Last</a>
</li>
</ul>
</div>
</div>
</form>
</div>
</div>
This is a very common mistake of not understanding asynchronous calls.
HistoryFactory.getHistory(vm.includeCancelled).then({}) is async, meaning that it will make the call and then continue executing code after the async call. When the async call has finished, the code inside .then({}) will then execute which could be 5 milliseconds or 5 seconds.
So here:
function activate() {
getHistory(); // async call, doesn't wait
vm.setPage(1); // executed immediately after, data not ready
}
Needs to be:
function activate() {
getHistory();
}
And changegetHistory() to:
function getHistory() {
HistoryFactory.getHistory(vm.includeCancelled).then(
function(response) {
_.each(response.data, function(upload) {
upload.inProgress = upload.status && ['INPROGRESS','NEW'].indexOf(upload.status.statusCd.trim()) > -1;
});
vm.uploads = response.data;
if($state.params.reupload){
uploadProductionData();
$state.params.reupload = false;
}
// Now call setPage after data is finished
vm.setPage(1);
});
}

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

Categories