Dynamic Table in Angular JS from json - javascript

I am trying to generate a dynamic table from Angular JS by receiving a response from Spring Rest Service.
This is my code:
// JavaScript Document
var app = angular.module("SDLC", []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
var urlBase = "http://localhost:8080";
app.controller('projecttable_controller', function($scope, $http) {
$scope.ordered_columns = [];
$scope.all_columns = [{
"title": "Project Name",
"type": "string"
}, {
"title": "Project Description",
"type": "string"
}, {
"title": "Owner",
"type": "string"
}, {
"title": "Start Date",
"type": "string"
}, {
"title": "End Date",
"type": "string"
},{
"title": "Record ID",
"type": "string"
}];
$http.get(urlBase+'/hello?input=raina').
success(function(data) {
//alert(data);
$scope.data=data;
alert($scope.data);
});
$scope.$watch('all_columns', function() {
update_columns();
}, true);
var update_columns = function() {
$scope.ordered_columns = [];
for (var i = 0; i < $scope.all_columns.length; i++) {
var column = $scope.all_columns[i];
$scope.ordered_columns.push(column);
}
};
});
<div class="btn-box-row row-fluid">
<table class="table table-striped">
<thead>
<tr>
<th ng-repeat="c in ordered_columns">{{ c.title }}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="ds in data">
<td ng-repeat="c in ordered_columns">{{ d[c.title] }}</td>
</tr>
</tbody>
</table>
</div>
There are no errors in the console. The table headers are displayed correctly. However, the data does not get populated in the table. If I hardcode the json in $scope.data, the table gets populated properly. Any help would be appreciated.

When you fetch your GET response, you write $scope.data = data; and you do nothing with $scope.data
change:
$http.get(urlBase+'/hello?input=raina').
success(function(data) {
//alert(data);
$scope.data=data;
alert($scope.data);
});
to:
$http.get(urlBase+'/hello?input=raina').
success(function(data) {
//alert(data);
$scope.all_columns=data;
alert($scope.data);
});
Because I see you populate your table from $scope.all_columns

Related

how to render columns from `dataSrc` function in datatable?

i want to show data from API into datatable using AJAX Request, this is my API response:
{
"title": "success",
"data": {
"name": "yogi",
"email": "yogi#gmail.com",
"activity": [
{
"name": "pergi"
},
{
"name": "belanja"
},
{
"name": "makan"
},
{
"name": "tidur"
}
]
}
}
and this is my datatable script:
$(document).ready(function () {
$("#activity-list").DataTable({
processing: true,
serverSide: true,
ajax: {
url: `${baseurl}/api/user/${user_id}/activity`,
dataSrc: function (json) {
let results = [];
for (let i = 0; i < json.data.activity.length; i++) {
results.push({
name: json.data.name,
email: json.data.email,
activity: json.data.activity[i].name,
});
}
return results;
},
},
});
});
why the data doesn't appear, instead i got error message?
The only thing you are missing is the columns option, which maps your results array to the HTML table's columns:
$("#activity-list").DataTable({
processing: true,
serverSide: true,
columns: [
{ data: "name" },
{ data: "email" },
{ data: "activity" }
],
ajax: {
url: '[my test URL here]',
dataSrc: function (json) {
let results = [];
for (let i = 0; i < json.data.activity.length; i++) {
results.push({
name: json.data.name,
email: json.data.email,
activity: json.data.activity[i].name,
});
}
return results;
}
}
});
This assumes you have a HTML table defined which already has the column headers you want to display:
<table id="activity-list" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Activity</th>
</tr>
</thead>
</table>
(Or, you could add those headings to the DataTables columns option using title, if you prefer.)

Datatable - DOM sourced Object array will not load data

I'm trying to initialise a datatable using an object array located in the DOM
I have simple datatable initialisation code:
$(document).ready(function () {
$('#ManageSubReps').DataTable({
data: GetSRData(),
columns: [
{ "data": "username" },
{ "data": "AspNetUserRoleName" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "State" },
{ "data": "Zip" },
{ "data": "EmailAddress" },
{ "data": "HomePhone" },
{ "data": "CellPhone" },
{ "data": "New_Rep" },
{ "data": "Stand_By" },
{ "data": "DateApproved" },
{ "data": "AspNetUserID" }
]
});
});
My GetSRData function looks like this:
function GetSRData() {
return #Html.Raw(Model.JsonData)
}
My server side code looks like this:
public ActionResult ManagerSubReps(){
var model = new ManageSubRepsViewModel();
model.JsonData = JsonConvert.SerializeObject(new {data = _iManageSubRepsManager.GetSubRepsAsync(Session["CID"])});
return View(model);
}
A snipped of my data looks like this:
{"data":[{"username":"01001MC","MASTER":null,"Name":"A name","Address":"105 Address Dr.","City":"Agawam","State":"MA","Zip":"89898","EmailAddress":"blerb#yahoo.com","HomePhone":"","CellPhone":"8767878767","New_Rep":"False","Stand_By":"False","DateApproved":null,"AspNetUserID":null,"AspNetUserRoleName":null},{"username":"01002RG","MASTER":"False","Name":"Blooby palooby","Address":"7 Eaton drive, gumbie#Gmail.Com","City":"Amherst","State":"MA","Zip":"35656","EmailAddress":"chumpy#GMAIL.COM","HomePhone":"","CellPhone":"8986786654","New_Rep":"False","Stand_By":"False","DateApproved":null,"AspNetUserID":null,"AspNetUserRoleName":null}]}
HTML:
<table id="ManageSubReps" class="compact display">
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th class="dt-left">Name</th>
<th class="dt-left">Address</th>
<th class="dt-left">City</th>
<th>State</th>
<th>Zip</th>
<th class="dt-left">Email</th>
<th>Home Phone</th>
<th>Cell Phone</th>
<th>New Rep</th>
<th>Stand By</th>
<th>Approved Date</th>
<th></th>
</tr>
</thead>
</table>
When I return my data and try to initiliase the datatable, two things can happen:
If I remove the "data" part of the Json object then datatales will render the datatables but will not have any data in
If I leave the "data" part of the Json object then datatables will give me the error: 'Request unknown parameter '0' for row 0, column 0'. Which basically means that it cannot distinguish the data and form the datatable with the data.
I have checked the column data and it matches perfectly fine. I cannot figure out what the issue is.
Can anyone help?
EDIT: I know the issue has something to do with the data being a string, as I call HTML.Raw() on it. However, Im unsure of how to pass the data from the model without this
try ajax instead of data & fully qualified url(controller/api method) for getting ajax data:
$(document).ready(function() {
$('#ManageSubReps').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "ManagerSubReps",
columns: [
{ "data": "username" },
{ "data": "AspNetUserRoleName" },
{ "data": "Name" },
{ "data": "Address" },
{ "data": "City" },
{ "data": "State" },
{ "data": "Zip" },
{ "data": "EmailAddress" },
{ "data": "HomePhone" },
{ "data": "CellPhone" },
{ "data": "New_Rep" },
{ "data": "Stand_By" },
{ "data": "DateApproved" },
{ "data": "AspNetUserID" }
]
} );
} );
refer https://datatables.net/examples/server_side/object_data.html for more details.

Javascript Datatables generating HTML link using render function on JSON data

I got a html table:
<table id="dattable" class="table table-striped table-bordered hover" cellspacing="0" >
<thead>
<tr>
<th>Name</th>
<th>Industry</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
and it is populated by JSON data. I want to use the render function to make items in the name column have a HTML link using the id field but it is not working.
var data2 =[
{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
},
{
"id":"1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}
];
$(document).ready(function() {
var table = $('#dattable').DataTable( {
data: data,
columns: [
{ data: 'name', "render": ""+[, ].name+""}, //render function
{ data: 'industry__name' },
{ data: 'cost' }
],
} );
} );
Based on your code, I think you need to change the definition of the column that generates the custom text you want. Also, I modified the call to render to use the function version.
var data2 = [{
"id": "0",
"name": "Jack Spicer",
"industry__name": "System Architect",
"cost": "$3,120",
}, {
"id": "1",
"name": "Sean Spice",
"industry__name": "Motormouth",
"cost": "-$5,300",
}];
$(document).ready(function() {
var table = $('#dattable').DataTable({
data: data2,
columns: [{
'data': null,
'render': function(data, type, row, meta) {
return '<a href=' + data.id + '>' + data.name + '</a>';
}
}, {
data: 'industry__name'
}, {
data: 'cost'
}]
});
});
You can take a lot at this as well, to see the changes I applied: https://jsfiddle.net/dr3hcd9j/

Ng-repeat datas from 2 json Angular

I try to get data from 2 jsons and list it in table :
1st 'names.json':
[
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "45%"
},
{
"name": "CCCCC",
"down": "12%"
}
]
Second 'data.json'
[
{
"data": "25-12-2014"
}
]
Javascript:
app.service('service', function($http, $q){
this.getNames = function () {
var datas = $http.get('data,json', { cache: false});
var names = $http.get('names.json', { cache: false});
return $q.all([datas, names]);
};
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.names.data;
$scope.datas = data.datas.data;
});
Now i must show it in table HTML :
div ng-controller="FirstCtrl"
<table>
<tbody>
<tr ng-repeat="name in names.concat(datas)">
<td>{{name.name}}</td>
<td>{{name.data}}</td>
</tr>
</tbody>
</table>
</div>
I try concat() but it dont work, is there any method to show in table datas from 2 arrays by ng-repeat?
Thanks for answers in advance!

How to add elements from a JSON array to a grid using Angular.js

I have a JSON array in a file data.json which is as :
var info = [{
"place": "Turkey",
"username": "jhon"
}, {
"place": "Dubai",
"username": "bruce"
}, {
"place": "Italy",
"username": "Wayne"
}];
I am able to access these using a loop and check with the help of an alert box.. However, I wish to display the contents in the form of a table. I could use JavaScript or as somebody suggested to me I could also use Angular.js. Any idea on what way I could get along with will be easier?
if you going to use angular just for displaying the JSON as a table, then it would be a overkill.
you can do it in plain javascript itself easily.
We can create each cell of the table with javascript and append it into a table dynamically.
function showInfo() {
var table = document.getElementById('info');
info.forEach(function(obj) {
var row = document.createElement('tr'),
col1 = document.createElement('td'),
col2 = document.createElement('td'),
place = document.createTextNode(obj.place),
username = document.createTextNode(obj.username);
col1.appendChild(place);
col2.appendChild(username);
row.appendChild(col1);
row.appendChild(col2);
table.appendChild(row);
});
document.body.appendChild(table);
}
Here is the sample fiddle
Update
seems forEach is not supported in IE. here is another version which uses for loop instead of forEach construct
function showInfo() {
var table = document.getElementById('info');
for (var i=0; i< info.length; i++) {
var obj = info[i],
row = document.createElement('tr'),
col1 = document.createElement('td'),
col2 = document.createElement('td'),
place = document.createTextNode(obj.place),
username = document.createTextNode(obj.username);
col1.appendChild(place);
col2.appendChild(username);
row.appendChild(col1);
row.appendChild(col2);
table.appendChild(row);
}
document.body.appendChild(table);
}
Here is the updated sample fiddle
You can import the data with a script tag:
<script src="data.json"></script>
And then use angularjs to display the data:
<script>
angular.module('mainApp', [])
.controller('mainCtl', function($scope) {
$scope.info = info;
});
</script>
<div ng-app="mainApp" ng-controller="mainCtl">
<table border="1" width="300">
<tr><td>Place</td><td>Username</td></tr>
<tr ng-repeat="n in info">
<td>{{n.place}}</td>
<td>{{n.username}}</td>
</tr>
</table>
</div>
http://jsfiddle.net/hdbu1ffs/
Here is how you could accomplish this with Angular, and here is a working plunker of the code below:
data.json
[
{
"place": "Turkey",
"username": "jhon"
},
{
"place": "Dubai",
"username": "bruce"
},
{
"place": "Italy",
"username": "Wayne"
}
]
Controller
app.controller('MainCtrl', function($scope, $http) {
$scope.info = null;
$http.get("data.json").success(function (data) {
$scope.info = data;
});
});
View
<body ng-controller="MainCtrl">
<table>
<tr>
<th>Place</th>
<th>Username</th>
</tr>
<tr ng-repeat="thing in info">
<td>{{thing.place}}</td>
<td>{{thing.username}}</td>
</tr>
</table>
</body>
you can solve easily by using angularjs:
in data.json:
[
{
"place": "Turkey",
"username": "jhon"
},
{
"place": "Dubai",
"username": "bruce"
},
{
"place": "Italy",
"username": "Wayne"
}
]
Controller:
angular.module('app', []).controller('SolutionController', ['$scope', '$http',
function($scope, $http) {
$http.get("data.json").then(function(infos) {
$scope.infos = infos;
}, function(error) {
$scope.infos = null;
});
}
]);
and view:
<body ng-controller="SolutionController">
<table>
<tr>
<th>Place</th>
<th>User Name</th>
</tr>
<tr data-ng-repeat="info in infos">
<td data-ng-bind="info.place"></td>
<td data-ng-bind="info.username"></td>
</tr>
</table>
</body>

Categories

Resources