ngTable with server side loading doen't update - javascript

I'm using ngTable to display a large table with data coming from the server. The initial data is displayed correctly. When I try sorting by a column or try going to the next page there is a request and correct response being sent and received, the getData function resolves it but the table isn't being updated in any way. It just shows the first page with the initial data.
HTML:
<table class="table table-bordered" ng-table-dynamic="table.detailsParams with table.cols" >
<tr ng-repeat="row in $data track by $index">
<td ng-repeat="col in $columns">{{::row[col.field]}}</td>
</tr>
</table>
JS:
scope.$on('campaign-changed', function (event, args) {
scope.campaign = args.campaign;
scope.campaign.createdAt = moment(scope.campaign.createdAt).format('DD MMM, YYYY')
scope.table.detailsParams = new NgTableParams({
count: 10,
sorting: { campaignName: "desc" }
}, {
getData: function (params) {
// ajax request to api
if (typeof params.total() == 'undefined' || params.total() == 0) {
ajaxSrv.getDetailsTotalCount(scope.campaign.id, function (data) {
params.total(data.data[0]);
})
}
var req = ajaxSrv.getCampaignData(params.url(), scope.campaign.id).then(function (response) {
return $q.resolve(response.data.data);
})
return $q.resolve(req);
}
});
})

Related

Get DataTables data from both local and REST sourced data

I want to use the jquery pluging datatables and complement local data through an external REST ressource.
My table has to columns, Id and RestCalledValue:
<table id="table">
<thead>
<tr>
<th>Id</th>
<th>RestCalledValue</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My js has an object data, which holds my local data:
let data = [
{
"id": 1
},
{
"id": 2
}
]
My datatables initialisation looks like below: i want to give the second column the returned value from the function getRestDataForId (id).
$(function () {
var table = $('#table').DataTable({
data: data,
columns: [
{
data: "id"
},
{
data: function (row, type, set, meta) {
getRestDataForId(row.id);
},
defaultContent: "-"
}
]
});
});
function getRestDataForId(id) {
fetch('https://jsonplaceholder.typicode.com/todos/' + id)
.then(response => response.json())
.then(data => data.title)
}
I constructed a fiddle here:
https://jsfiddle.net/mxhdwfz6/2/
I must be treating the promise wrong. Looking forward for your input!

Axios Vue.js table is not reflecting response data

I have a function which I am calling whenever a file is uploaded in order to refresh my table which holds the files.
The response.data is coming back with the correct data but my table is not reflecting it. Any idea what I could do in order to force update my table to show the new entries?
If I refresh the page, the data comes back correct.
function GetFileList(intID) {
//$("#fileuploadstbl").empty();
var ItemsVue = new Vue({
el: '#fileUploadContent',
data: {
items: []
},
mounted: function () {
var self = this;
axios.get("getUploads.ashx")
.then(response => {
self.items = response.data
}, function (err) {
console.log('error');
console.log(err.status);
console.log(err.response.status);
})
.catch(err => {
console.log('error');
console.log(err.status);
});
}
});
$("#fileUploadContent").show();
}
And this is how I bind my <tr>:
<tr
v-for="item in items" class="tddata"
v-bind:data-ID="item.ID"
v-bind:data-Uploadid="item.Uploadid"
>
<td>{{item.Filename}}</td>
<td
style="cursor: pointer;text-align:center;"
v-on:click="ViewFile(item.Filepath,item.Filename)"
>
View File
</td>
<td
style="cursor: pointer;text-align:center;"
v-on:click="DeleteFile(item.ID,item.guid,item.Filepath,item.Filename)"
>
View File
</td>
<td style="text-align:center;">{{item.UploadedBy}}</td>
</tr>
It will automatically update for your case. Maybe you can check is your response.data save in your "items". If still cannot, maybe try to use the forceupdate function
this.$forceUpdate();
This works for me
//HTML
<tr v-for="user in users" :key="user.id" v-bind="users_model">
//In your method
axios.get('sample-domain..com').then(response => {
this.users = response.data.data
this.users_model++
})

angularJS ng-table $data not recognized in ng-repeat and no headers is shown

I want to use ng-table but I am having problem with headers and ng-repeat
<table ng-table="tableParams" show-filter="true" template-pagination="custom/pager" class="table table-bordered table-striped b-t b-light">
<tbody>
<div ng-repeat="row in $data track by row.Id" class="table-row">
<div data-title="'pair'" filter="{ 'pair': 'text' }" sortable="'pair'" class="table-name-cell table-cell pointer ui-sortable-handle">
nothing is shown.If I use
<div ng-repeat="row in tableParams.data track by row.Id" class="table-row">
then I can see data but without any headers. Why I can not see headers by default? And why $data is not working as is written in docs
DataResults DataResults: T[] & { visibleColumnCount: number; } Defined
in src/core/data/results.ts:13 The augmented data row array displayed
by the table. Note: this array is made available to the table templete
as the $data fiel
EDIT:
I am not using tr, td tags but div tags. Is this important?
AngularJS code
$scope.tableParams = new NgTableParams({
page: 1,
count: 10
/*sorting: {
time: 'asc'
}*/
}, {
total: 0,
filterDelay: 300,
getData: function (params) {
return service.search(urlAddress, (params.page() - 1) * params.count(), params.count(), params.filter(), params.sorting())
.$promise.then(
// success
function (result) {
scope.items = result.items;
params.total(result.totalCount);
scope.$root.showSpinner = false;
return result.items;
},
//error
function (error) {
scope.$root.showSpinner = false;
webMessageService.addError('Error while reading data: ' + error.data);
}
);
}
});
$scope.tableParams.reload();

controller to populate the data into the datatable using angular js

I want to populate the data into the datatable but no data is getting populated into the table.
Error I'm getting on debugging is:
Uncaught TypeError: Cannot read property 'getContext' of null
html:
<table class="display table table-bordered table-striped" id="example">
<thead>
<tr>
<th>User Name</th>
<th>Email Id</th>
<th>Group Name</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.user}}</td>
<td>{{item.email}}</td>
<td>{{item.groupName}}</td>
<td>{{item.createdAt}}</td>
</tr>
</tbody>
</table>
controller:
(function () {
"use strict";
angular.module('app').controller('superAdminController', function ($scope, AuthenticationService, $timeout, $location, $http, myConfig) {
AuthenticationService.loadSuperAdmin(function (response) {
if (response.data.success) {
$scope.populateTable(response.data);
console.log(response.data);
} else {
$scope.items = [];
}
});
$scope.populateTable = function (data) {
$scope.items = data.loadSuperAdminData;
$timeout(function () {
$("#example").dataTable();
}, 200)
};
});
}());
In controller, you can populate your server response like this.
$.post(MY_CONSTANT.url + '/api_name',{
access_token: accessToken
}).then(
function(data) {
var dataArray = [];
data = JSON.parse(data);
var lst = data.list;
lst.forEach(function (column){
var d = {user: "", email: "", group: "", created: ""};
d.user = column.user;
d.email = column.email;
d.groupName = column.group;
d.createdAt = column.created;
dataArray.push(d);
});
$scope.$apply(function () {
$scope.list = dataArray;
// Define global instance we'll use to destroy later
var dtInstance;
$timeout(function () {
if (!$.fn.dataTable) return;
dtInstance = $('#datatable4').dataTable({
'paging': true, // Table pagination
'ordering': true, // Column ordering
'info': true, // Bottom left status text
// Text translation options
// Note the required keywords between underscores (e.g _MENU_)
oLanguage: {
sSearch: 'Search all columns:',
sLengthMenu: '_MENU_ records per page',
info: 'Showing page _PAGE_ of _PAGES_',
zeroRecords: 'Nothing found - sorry',
infoEmpty: 'No records available',
infoFiltered: '(filtered from _MAX_ total records)'
}
});
var inputSearchClass = 'datatable_input_col_search';
var columnInputs = $('tfoot .' + inputSearchClass);
// On input keyup trigger filtering
columnInputs
.keyup(function () {
dtInstance.fnFilter(this.value, columnInputs.index(this));
});
});
// When scope is destroyed we unload all DT instances
// Also ColVis requires special attention since it attaches
// elements to body and will not be removed after unload DT
$scope.$on('$destroy', function () {
dtInstance.fnDestroy();
$('[class*=ColVis]').remove();
});
});
});

Data Table with Angularjs

I am using angularjs with MVC5 (.net) for creating single page website. I have problem to bind data with "data table(jquery)"
When first time bind data in to table at that time it's work fine but when i edit the record and rebind the data with data table at that time getting issue.
my code like bellow:
HTML
<table id="dt_Tarnsaction_Lunch" class="notinit">
<thead>
<tr>
<th >Employee Id</th>
<th >Edit</th>
</tr>
</thead>
<tbody id="TLunch">
<tr ng-repeat="TableRow in DashTranTableRows}" on-finish-tranlunch>
<td>{{TableRow.trancol_emplid}}</td>
<td >
<button ng-click="EditRecord(TableRow.trancol_dailytranspk)">
Edit
</button>
</td>
</tr>
</tbody>
</table>
"on-finish-tranlunch" Directive Code
appRoot.directive('onFinishTranlunch', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatTranlunchFinished');
});
}
}
}
});
My Code In Controller
$scope.LoadData();
var OTransLunchTable;
$scope.$on('ngRepeatTranlunchFinished', function (ngRepeatTranlunchFinishedEvent)
{
if (!null)
{
if ($("#dt_Tarnsaction_Lunch").hasClass("init"))
{
OTransLunchTable.fnDraw();
}
else
{
$("#dt_Tarnsaction_Lunch").removeClass("notinit");
$("#dt_Tarnsaction_Lunch").addClass("init");
OTransLunchTable = $('#dt_Tarnsaction_Lunch').dataTable({
"sPaginationType": "bootstrap",
"sDom": "R<'dt-top-row'Clf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
"fnInitComplete": function (oSettings, json) {
$('.ColVis_Button').addClass('btn btn-default btn-sm').html('Columns <i class="icon-arrow-down"></i>');
}
});
}
$('#dt_Tarnsaction_Lunch').width('100%');
}
else
{
$(".loading").hide();
alert("Error - Data can not be load");
}
});
My Code In Controller for load data first time as well as after edit record(both time i am using same method)
$scope.LoadData = function ()
{
myResource.getDashTableRows().then(function (d)
{
$scope.DashTranTableRows = d.data;
},
function (error) {
$(".loading").hide();
window.location = "login";
});
}
So, finally data loaded first time well and data table works fine at the first time but When i am edit record and load updated data at that time data table not loaded with updated data and also edit button not works.. :(
My JSON Format like bellow
[
{
"trancol_emplid": "a1",
"trancol_dailytranspk": 1
},
{
"trancol_emplid": "a2",
"trancol_dailytranspk": 2
},
{
"trancol_emplid": "a3",
"trancol_dailytranspk": 3
},
{
"trancol_emplid": "a4",
"trancol_dailytranspk": 4
},
{
"trancol_emplid": "a5",
"trancol_dailytranspk": 5
},
{
"trancol_emplid": "a6",
"trancol_dailytranspk": 6
}
]
My Service factory for load data from Server
angular.module('GratSyncSite').factory('myResource', function ($http)
{
var myResource =
{
getDashTableRows: function ()
{
$(".loading").show();
var promise = $http.get(WEBRESOURCEURL).success(function (response)
{
return response;
});
return promise;
}
}
});
Where are you posting your data? Is data even being received on server side?
On thing to note: MVC is not the best framework for SPAs. I would use ASP.NET WEB API (2.1) for server side.
That way API can be reused by 3rd party if you ever consider to open it to public.

Categories