How to use Jquery Datatable with AngularJs to export table - javascript

I am working on angular website where I need to export table's data to pdf.
I want to use jQuery datatables for it as it alse add some more features like paging,searching and sorting, but getting this error "Error: [$injector:unpr]" on browser's console, even I am not sure using ng-table will make it to datatable or not.
I have also tried using jquery plugin pdfmake but it only make signle page pdf and failed if table have larger data.
Please help and TIA.
Html :-
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/1.0.0/ng-table.min.js"></script>
<table id="myYealyGrid" ng-class="myYealyGridClass" class="table table-responsive gridtable" ng-table="yearly_Table">
<thead>
<tr>
<th>Customer Name</th>
<th>Year</th>
<th>Total Amount($)</th>
</tr>
</thead>
<tbody>
<tr ng-show="YearlyReport.length !=0" ng-repeat="reportrow in YearlyReport" ng-init="setTotal(reportrow)">
<td>{{reportrow.CustomerName}}</td>
<td>{{reportrow.Month}}</td>
<td>{{reportrow.TotalAmount}}</td>
</tr>
<tr ng-show="YearlyReport.length ==0">
<td><small class="nodata">No data found.</small></td>
<td></td>
<td></td>
</tr>
</tbody>
<tfoot>
<tr ng-show="YearlyReport.length !=0" class="bg-warning">
<td class="td-font-bold-custm">Total</td>
<td></td>
<td class="td-font-bold-custm">{{gridTotalAmount | number:2}}</td>
</tr>
</tfoot>
</table>
AngularJs:-
var appKitchenOrderReport = angular.module("myKitchenOrderReportApp", ['ngTable']);
appKitchenOrderReport.controller("myKitchenOrderReportCntrl", function ($scope, $window, $timeout, myKitchenOrderReportService, ngTableParams) {
var getData = myKitchenOrderReportService.SearchData($scope.CustomerName, $scope.Year);
getData.then(function (kitchenreportdata) {
var yearlyGridData = kitchenreportdata.data.OrderYearlyReport;
$scope.yearly_Table = new ngTableParams({
page: 1,
count: 10
}, {
total: $scope.yearlyGridData.length,
getData: function ($defer, params) {
$scope.YearlyReport = $scope.yearlyGridData.slice((params.page() - 1) * params.count(), params.page() * params.count());
$defer.resolve($scope.YearlyReport);
}
});
}, function () {
alert('Error in getting data');
});
});
appKitchenOrderReport.service("myKitchenOrderReportService", function ($http) {
this.getKitchenOrderReportData = function () {
var response = '';
return $http.get("GetOrderReport"); };
this.SearchData = function (CustomerName, Year)
{
var GetParams = new Object();
GetParams.CustomerName = CustomerName;
GetParams.Year = Year
var response = $http({
method: "post",
url: "GetOrderReport",
data: '{model: ' + JSON.stringify(GetParams) + '}',
});
return response;
}
});

you can Use $('#myYealyGrid').DataTable(); to initialize your datatable .
But Use just befor , when you Put data into the HTML table .
It will automatically initialize your Datatable.
Try it and let me know is it working or not .

Related

Populate Table Content with Data From Ajax

I've been searching on how to achieve this. I got a lot of info from this site, but all couldn't help.
I'm trying to populate a table with the data I got from PHP File Using Ajax
I've been able to get the data, at least into the console. But when i try sending it to the the table, nothing is shown. No errors shown, Just blank.
console.log(newarr)
brings
gives this answer (image)
But when I do this $("#report").html(newarr);, nothing happens.
Here is the code:
ajax
$.post('./process/assetReport.php', data, function(data) {
genData = JSON.parse(data);
var newarr;
for (var key in genData) {
if (data.hasOwnProperty(key)) {
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
php
foreach($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);
The table I need to populate
<table class="table" id="reportTable">
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="report">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-success" id="printReport"><i class="glyphicon glyphicon-print"></i> Print</button></td>
</tr>
</tfoot>
</table>
I hope my question is explanatory enough
Thank you
I have created a stub of a JSON array, and shown how to loop through it appending rows to your table as you go. I excluded your key check, as I wasn't sure the relevance. A variation of this code should reside in the callback to your $.post()
data = [{
asset: "steve",
staff: "steve",
cost: '$999,999.99'
}, {
asset: 'bob',
staff:"bob",
cost: '$0.99'
}];
var $row = $("<tr><td></td><td></td><td></td></tr>"); //the row template
var $tr;
$.each(data, function(i, item) {
$tr = $row.clone(); //create a blank row
$tr.find("td:nth-child(1)").text(item.asset); //fill the row
$tr.find("td:nth-child(2)").text(item.staff);
$tr.find("td:nth-child(3)").text(item.cost);
$("#report").append($tr); //append the row
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Asset Name</th>
<th>Assigned To</th>
<th>Cost</th>
</tr>
</thead>
<tbody id='report'>
<tbody>
</table>
I think you need to user genData[0] instead of genData as your are using $useData[] inside php or user $useData instead of $useData[]
So the code should be look like followings:
$.post( './process/assetReport.php', data, function (data) {
genData = JSON.parse(data);
var newarr;
for(var key in genData[0]) {
if(data.hasOwnProperty(key)){
newarr = genData[key];
//console.log(newarr);
$("#report").html(newarr);
}
}
});
And the php:
foreach ($all as $item) {
$assetid = $item['assetid'];
$staffid = $item['staffid'];
$row2 = $user->showone('assets', 'assetid', $assetid);
$row3 = $user->showone('staff', 'staffid', $staffid);
$useData[] = array(
'asset' => $row2['name'],
'staff' => $row3['name'],
'cost' => $item['cost']
);
}
echo json_encode($useData);

How I can order data pre date

I would like to know how I can do order data from API pre-date very time.
How its should be:
<table>
<tr>
<th>2017-02-17</th>
</tr>
<tr>
<td>some date</td>
<td>some date</td>
<td>some date</td>
</tr>
<tr>
<th>2017-02-15</th>
</tr>
<tr>
<td>some date</td>
<td>some date</td>
<td>some date</td>
</tr>
</table>
example:
URL API: http://api.tradingeconomics.com/calendar?c=guest:guest
My code:
$.ajax({
url: "url",
type: "Get",
datatype: "JSON",
contentType: "application/json",
error : function (data) { console.log("error:" + data) },
success: function (response) {
response.forEach(function (data) {
$('.top_table').append(
"<tr>" +
"<th>DATE</th>" +
"</tr>" +
"<tr id='content'>" +
"<td>some text....</td>" +
"<td>some text....</td>" +
"<td>some text....</td>" +
"<td>some text....</td>" +
"</tr>"
);
});
console.log(response);
}
});
But its print like:
date
result
date
result
How I can do it?
I don't know if I've understood your question very well, but I think that could give you some tips.
Your API returns an Array of Objects if you make and Ajax GET request, so you can order this Array before inserting the content into the DOM:
The next example order the data in descending order comparing the Date parameter, there is another date parameter called LastUpdate, I don't know if you want to use it in your logic.
$.get("https://api.tradingeconomics.com/calendar?c=guest:guest", function (data) {
//---Order the array received from the server
data.sort(function (a, b) {
return (new Date(a.Date)) - (new Date(b.Date));
});
//---The data is ordered, you can insert it into the DOM
});
In the other hand, your code inserts a row with the header content and a row with the body content in each iteration, this is not correct. You need to add all the header texts in a single row and each item of the Array needs to be inserted in separated rows.
Here you have a working example to give you an idea of the process:
https://jsfiddle.net/elchininet/ym8qp415/
EDIT: Seeing your comments, I understand now that you want to grouping the data not just ordering it. I recommend you to use the reduce method of the Array class to create a new data separated by dates and after that you can insert the data in the table:
var regdate = /^(\d{4}\-\d{2}\-\d{2})T(\d{2}:\d{2}:\d{2})$/;
//---Sort the data from the server
data.sort(function (a, b) {
return (new Date(a.Date)) - (new Date(b.Date));
});
var group = data.reduce(function (before, current) {
var day = current.Date.replace(regdate, "$1");
var hour = current.Date.replace(regdate, "$2");
if (!before[day]) {
before[day] = [];
}
current.Hour = hour;
before[day].push(current);
return before;
}, {});
//---The data is ordered and grouped, you can insert it into the DOM
Working example with fake data (Because of the example in the API returns only one day):
http://jsfiddle.net/elchininet/nvv4fnon/
Without a plugin, this is going to be difficult to achieve unless the "calendar" information is pulled from a database, it may be worth sorting in PHP, loading and displaying the data in jQuery
<script type="javascript">
$(function() {
$("BODY").on("click", "TH[data-orderby]", function() {
var order = $(this).data("orderby") || "date";
var parent = $(this).parents("table").parent();
$.ajax({
url: 'calendar?c=guest:guest',
data: 'order-by=' + URLEncode(order),
type: 'POST',
success: function(response) {
parent.html(response);
},
error: function(event, request, settings) {
console.warn("Ajax Error", request);
}
})
});
});
</script>
<div class="parent">
<table>
<thead>
<tr>
<th>Heading</th>
<th data-orderby="date">Date</th>
<th>Title</th>
<th data-orderby="last_updated">Last Updated</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</tbody>
</table>
Because we use $("BODY").on("click", "TH[data-orderby]"), even when the data is reloaded from the server, the sort functionality will remain.
I hope this helps.

Dynamic table with JSON data and sticky collapsible rows

I'm using Angular 1 with a factory that polls a REST API for JSON data. This JSON then populates a table with ng-repeat-start, and using ng-repeat-end I have a hidden table row with additional data.
Seems rather ordinary to me.
But the problem is, when I poll the API every 5 or 10 seconds, how can I keep the collapsible table row open when the next poll occurs?
In most cases the data does not change, so there's no reason to close the collapsible row, yet it closes at every poll that my factory makes.
Here's an example of one of the tables.
<table class="pure-table pure-table-horizontal alerts-table" id="alert-nagios-host-table">
<thead>
<tr>
<th>Hostname</th>
<th>Status</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr class="parent-row" ng-repeat-start="alert in alerts" ng-click="child.expanded = !child.expanded">
<td>{{alert.hostname}}</td>
<td ng-class="{3:'grayBg', 2:'redBg', 1:'yellowBg', 0:'greenBg'}[alert.state]">{{alert.status}}</td>
<td>{{alert.output}}</td>
</tr>
<tr class="child-row" ng-init="child.expanded = false" ng-show="child.expanded" ng-repeat-end>
<td colspan=4>Duration: {{alert.duration}}</td>
</tr>
</tbody>
</table>
Here is my factory that polls the data, and an example of one of the angular controllers.
mondashApp.factory('AlertsPoller', function ($http, $timeout) {
var data = {resp: {}, count: 0};
var count=0;
var poller = function (url, success) {
count++;
$http.get(url).then(function (responseData) {
data.count = count;
data.resp = responseData.data;
success(data);
$timeout(function () {poller(url, success);}, 5000);
});
};
return {
poller: poller
};
});
mondashApp.controller('nagiosHostAlertsCtrl', function nagiosHostAlertsCtrl($scope, AlertsPoller) {
AlertsPoller.poller('/alert/nagios/host', function(response) {
$scope.alerts = response.resp.alerts;
});
});

AngularJS view not updated after model updates

New to Angular, I am trying to save a form and update the view after calling a PUT or POST call to the backend. Once I receive an OK status from the backend, I am updating my models with the latest response. But only the model in the directive "ng-click" gets updated but others do not. Here is my code:
///HTML
<table class="footable table table-stripped toggle-arrow-tiny" data-page-size="8">
<thead>
<tr>
<th data-toggle="all">Release Title</th>
<th data-hide="all">Release Genre</th>
<th data-hide="all">UID</th>
<th data-hide="all">Classical</th>
<th data-hide="all">Tracks</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="album in vm.albums" footable>
// This one (album.data.title) gets updated but the other ones do not
<td ng-click="vm.editAlbum(album, $index)">{{album.data.title}}</small></td>
<td>{{album.data.genre}}</td>
<td>{{album.data.uid}}</td>
<td ng-if!="album.data.classical">No</td>
<td ng-if="album.data.classical">Yes</td>
<td>
<li ng-repeat="track in album.data.tracks">
<a ng-click="vm.selectTrack(album, track)">{{track.title}}</a>
</li>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<ul class="pagination pull-right"></ul>
</td>
</tr>
</tfoot>
</table>
Here is my controller:
// controller.js (Just pasting the saveRelease method that does the on-click event handling in HTML:
(function (){
angular.module('app.uploadedReleases').controller('UploadedReleasesController', UploadedReleasesController);
UploadedReleasesController.$inject = ['$http', '$log', '$scope', '$state', '$rootScope', 'APP_CONFIG'];
function UploadedReleasesController ($http, $log, $scope, $state, $rootScope, APP_CONFIG){
var vm = this;
vm.albums = []; // list of all albums
vm.albumPriority = [0, 4, 6, 8, 10];
vm.getAlbumTracks = getAlbumTracks;
vm.editAlbum = editAlbum;
vm.selectTrack = selectTrack;
vm.selected = {};
vm.saveRelease = saveRelease;
vm.testingAlbumSelected = false;
return init();
function init(){
$http.get('http://localhost:8080/api/releases').then(function(responseData){
//check the status from the response data.
vm.responseStatus = responseData.status;
if(vm.responseStatus !== 200){
//error message
}
// else, Parse the json data here and display it in the UI
for(var album in responseData.data){
vm.albums.push({slug: album, data: responseData.data[album]});
}
})
}
function getAlbumTracks(slug, index){
$http.get('http://localhost:8080/api/releases/' + slug).success(function(trackResponse){
//parse each album and get the track list
vm.showingAlbumIndex = index;
vm.albums.tracks = [];
vm.selected = {};
vm.selected.album = vm.albums[index];
vm.testingAlbumSelected = true;
for(var i = 0; i<trackResponse.tracks.length; i++) {
vm.albums.tracks.push(trackResponse.tracks[i]);
}
$log.debug(vm.albums.tracks);
vm.formAlbum = new Album(vm.selected.album.data.upc,
vm.selected.album.data.title,
vm.selected.album.data.label,
vm.selected.album.data.genre,
vm.selected.album.data.releaseType,
vm.selected.album.data.holdDate,
vm.selected.album.data.priority,
vm.selected.album.data.memo);
})
}
function selectTrack(album, track){
vm.selected.album = album;
vm.selected.track = track;
vm.testingAlbumSelected = false;
}
function editAlbum(album, index){
getAlbumTracks(album.slug, index);
vm.selected = album;
}
function saveRelease(){
// Call the PUT request to update the release metadata and refresh the page
// so that the Album list gets updated with the latest changes
var url = 'http://localhost:8080/api/releases/' + vm.selected.album.slug;
$http.put(url, vm.formAlbum).then(function(saveAlbumResponse){
if(saveAlbumResponse.status === 202){
//successfully saved response on backend
// Update the current models to show the newer data
vm.album.data = vm.formAlbum;
console.log("album array vm.albums = "+vm.albums);
}
})
}
})();
Any idea why ?
try remove "var vm=this" line. And rename vm.xxxx to $scope.xxxx in your controller.
in the view: remove the "vm."

Generating table from json in AngularJS

I'm trying to generate HTML table from json in AngularJS.
I receive JSON in format like this:
My Service for getting the data looks like this :
customAPI.getUsers = function() {
return $http({
method: 'JSONP',
url: 'http://arka.foi.hr/WebDiP/2013_projekti/WebDiP2013_069/api/admin/users.php'
});
};
and controller for that code looks like this
controller('usersController', function($scope, customAPIservice) {
$scope.filterName = null;
$scope.usersList = [];
/*Search*/
$scope.searchFilter = function(user) {
var keyword = new RegExp($scope.filterName, 'i');
return !$scope.filterName || keyword.test(user.korisnici.korisnik_ime) || keyword.test(user.korisnici.korisnik_prezime);
};
customAPIservice.getUsers().success(function(response) {
$scope.usersList = response.korisnici;
});
});
and my view looks like this :
<input type="text" ng-model="nameFilter" placeholder="Trazi..."/>
<h2 >Korisnici</h2>
<table>
<thead>
<tr>
<th colspan="6">Korisnici sustava</th>
</tr>
<th>Surname</th>
</thead>
<tbody>
<tr ng-repeat="user in usersList| filter: searchFilter">
<td>{{$index + 1}}</td>
<td>{{user.korisnik.korisnik_prezime}}</td>
<td>{{user.korisnik.korisnik_username}}</td>
</tr>
<tr ng-show="usersList == ''">
<td colspan="5">
<img src="img/ajax-loader.gif" />
</td>
</tr>
</tbody>
</table>
I think I messed up somewhere with binding the data with the view but I' still pretty new with angular so I can't find what is wrong. Also I've looked up over internet and couldn't find anything.Please help.
You are not correctly access the properties in your data. Use:
/*Search*/
$scope.searchFilter = function(user) {
var keyword = new RegExp($scope.filterName, 'i');
return !$scope.filterName || keyword.test(user.korisnik.korisnik_ime) || keyword.test(user.korisnik.korisnik_prezime);
};

Categories