How to convert table data into Json format in Angular - javascript

I am trying to convert data present in an HTML table into JSON link. I'm getting undefined values in object.
HTML code:
<table colspan="2" border="1">
<tr>
<th>Source</th>
<th>Destination</th
</tr>
<tr ng-repeat="col in MapCol">
<td>
<select ng-model="col.value" ng-init="col.value=MainData.headers[$index].header">
<option ng-selected="{{head.header == col.value}}" ng-repeat="head in MainData.headers">{{head.header}}
</option>
</select>
</td>
<td>{{col.ColName}}</td>
</tr>
</table>
<br/>
<button ng-click="map();">Map</button>
Controller code:
var app = angular.module("ShrTest", []);
app.controller("Test1", function ($scope) {
$scope.MainData = { "name": "1-06082015185338.txt", "headers": [{ "header": "Name" }, { "header": "Age" }, { "header": "Address" }], "records": [{ "Name": "Paul", "Age": "23", "Address": "1115 W Franklin" }, { "Name": "Bessy the Cow", "Age": "5", "Address": "Big Farm Way" }, { "Name": "Zeke", "Age": "45", "Address": "W Main St" }] };
$scope.MapCol = [{ "ColName": "Col1" }, { "ColName": "Col2" }, { "ColName": "Col3" }];
$scope.map=function(){
$scope.fields=[{"source":$scope.value,"destination":$scope.ColName}];
console.log(" $scope.fields..", $scope.fields);
}
});

JS
$scope.map=function(){
$scope.fields = [];
for(i in $scope.MapCol){
var obj = $scope.MapCol[i]; $scope.fields.push({"source":obj.value,"destination":obj.ColName})
}
console.log($scope.fields);
}
Here is Modified fiddle:
Demo Here
I hope this will help you.

Related

How deploy dynamic data into html table from json file?

The following code I have tried but its not working. I want to deploy data according to row id into table dynamically.So in future if someone make changes into json file then data must be displayed into table's column according the json data.For Instance, if I make changes in my json file day from monday to Friday then data must be displayed into Friday column without making any changes into javascript code.
var makeSchedule=
{
"schedule" : [
{"fitnessClass": "One",
"sessionType": "Push Up",
"duration": 1,
"allocatedTime": {
"group" : "A",
"day" : "mon",
"location" : "Main Hall",
"time": "11"
},
"alternativeTimes":
[
{"group" : "B",
"day" : "tues",
"location" : "Main Hall2",
"time": "11"}
]
},
{"fitnessClass": "Two",
"sessionType": "Running",
"duration": 1,
"allocatedTime": {
"group" : "A",
"day" : "weds",
"location" : "Main Hall 3",
"time": "9"
},
"alternativeTimes":
[
{"group" : "B",
"day" : "thurs",
"location" : "Main Hall 4",
"time": "9"}
]
},
{"fitnessClass": "Three",
"sessionType": "Pull Ups",
"duration": 1,
"day" : "thurs",
"location" : "Main Hall 3",
"time": "15"
}
]
}
window.addEventListener("load",function(){
makeSchedule.schedule.forEach(booked => {
if(booked.allocatedTime.day==='thurs')
{
document.getElementsByClassName('s9').innerHTML = `${booked.sessionType}`;
}
});
});
<table>
<tbody>
<tr id="mon">
<td class="dayRowHead">Monday</td>
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="tues">
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="thurs">
<td class="s9"></td>
<td class="s10"></td>
</tr>
</tbody>
</table>
This line:
if(booked.allocatedTime==='thurs')
Looks like it should be:
if(booked.allocatedTime.day ==='thurs')
According to the object you have.
document.getElementsByClassName('s9').innerHTML = ${booked.sessionType};
Update
#utkanos has pointed out that document.getElementsByClassName('s9').innerHTML returns a nodeList and not an HTMLElement, which is another problem. A more complete code chunk would look like this:
var makeSchedule = {
"schedule": [{
"fitnessClass": "One",
"sessionType": "Push Up",
"duration": 1,
"allocatedTime": {
"group": "A",
"day": "mon",
"location": "Main Hall",
"time": "11"
},
"alternativeTimes": [{
"group": "B",
"day": "tues",
"location": "Main Hall2",
"time": "11"
}]
},
{
"fitnessClass": "Two",
"sessionType": "Running",
"duration": 1,
"allocatedTime": {
"group": "A",
"day": "weds",
"location": "Main Hall 3",
"time": "9"
},
"alternativeTimes": [{
"group": "B",
"day": "thurs",
"location": "Main Hall 4",
"time": "9"
}]
},
{
"fitnessClass": "Three",
"sessionType": "Pull Ups",
"duration": 1,
"day": "thurs",
"location": "Main Hall 3",
"time": "15"
}
]
}
window.addEventListener("load", function() {
makeSchedule.schedule.forEach(booked => {
if (booked.allocatedTime && booked.allocatedTime.day === 'mon') {
document.querySelectorAll('.s9').forEach(el => {
el.innerHTML = `${booked.sessionType}`;
})
}
});
});
<table>
<tbody>
<tr id="mon">
<td class="dayRowHead">Monday</td>
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="tues">
<td class="s9"></td>
<td class="s10"></td>
</tr>
<tr id="thurs">
<td class="s9"></td>
<td class="s10"></td>
</tr>
</tbody>
</table>
Note that I used querySelectorAll() instead of getElementsByClassName(), and looped through the results with forEach(). Finally, I changed "thurs" to "mon", since "thurs" is only in booked.alternativeTimes.day and booked.day in your example data. I would suggest making your data object more uniform in structure so that you don't have to use a lot of conditionals to access the right data in the future. You should always be able, for example, to expect the "day" value to appear in the same place in each booked object.
you need to search for the class in the parent element
var x = document.getElementById("thurs");
x.getElementsByClassName("s9")[0].innerHTML = `${booked.sessionType}`;

Dynamically adding column in table

I am trying to add new column dynamically in the table. I have below object which is returned in response from web service api. How can I display dynamic columns where myArray object is getting appended with many other fields (new columns)
$scope.myArray = [
{
"contacts": [
{
"id": "1",
"contact": {
"name": "Sam",
"Email": "ddd#co.com",
"PhoneNo": 2355
}
},
{
"id": "2",
"contact": {
"name": "John",
"Email": "test#co.com",
"PhoneNo": 2355
}
}
]
}
];
I have tried looking into the example provided in some of the answers in google. In my below JSFIDDLE, I am getting only the key name but not the values. How can I achieve both key and value using ng-repeat where the key names are dynamic.
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.myArray = [
{
"contacts": [
{
"id": "1",
"contact": {
"name": "Sam",
"Email": "ddd#co.com",
"PhoneNo": 2355
}
},
{
"id": "2",
"contact": {
"name": "John",
"Email": "test#co.com",
"PhoneNo": 2355
}
}
]
}
];
});
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.min.js"></script>
<table ng-controller="myController" border="1">
<tr>
<th ng-repeat="(key, val) in myArray[0].contacts[0].contact">{{ key }}</th>
</tr>
<tr ng-repeat="row in myArray[0].contacts">
<td ng-repeat="(key, val) in row.contact">{{ val }}</td>
</tr>
</table>

DataTables Multiple Tables from Multiple JSON Arrays

I want to output two tables, each sourcing information from two separate arrays within the same JSON source, but for some reason my code doesn't work.
JSON Message:
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
HTML Code:
<table id="policies-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Score</th>
</tr>
</thead>
</table>
<table id="services-table" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Score</th>
</tr>
</thead>
</table>
JavaScript Code:
var the_url = "www.example.com"
var columnsDef = [
{ data : "name" },
{ data : "id" },
{ data : "score" }
];
$(document).ready(function() {
$('#policies-table').DataTable({
ajax : {
url : the_url,
dataSrc: "Policies"
},
columns : columnsDef
}),
$('#services-table').DataTable({
ajax : {
url : the_url,
dataSrc: "Services"
},
columns : columnsDef
})
});
You are not iterating through your JSON variable. As prabodhprakash suggested, writing "Policies" and "Services" won't help either.
I suggest you to take a look at this fiddle
You can initialize multiple datatables with the same syntax that you use for initializing a single one:
var json = {
"Policies": [{
"name": "A",
"id": "1",
"score": "0"
}],
"Services": [{
"name": "B",
"id": "2",
"score": "0"
}]
}
var policyTable = $("#policies-table").DataTable({
"data" : (json.Policies),
"columns": [
{ "data": "name" },
{ "data": "id" },
{ "data": "score" }]
});
var serviceTable = $("#services-table").DataTable({
"data" :(json.Services),
"columns": [
{ "data": "name" },
{ "data": "id" },
{ "data": "score" }]
});

Sorting is not working in ngTable when using nested json

I have created an application in angularjs with ngTable, The application is working fine but sorting is not working. My json structured is nested, but values are coming correctly with the table
Can anyone please tell me some solution for this
My code is as given below
JSFiddle
html
<div ng-controller="IndexCtrl">
<table border="1" ng-table="mytable">
<tbody ng-repeat="peop in peoples">
<tr ng-repeat="people in peop">
<td sortable="'id'" data-title="'Id'">{{people.id}}</td>
<td sortable="'desig'" data-title="'Desig'">{{people.desig}}</td>
<td sortable="'name'" data-title="'Name'">{{people.name}}</td>
<td sortable="'place'" data-title="'Place'">{{people.place}}</td>
</tr>
</tbody>
</table>
</div>
script
var app = angular.module('app', ['ngTable']);
app.controller('IndexCtrl', function ($scope, $filter, ngTableParams) {
$scope.peoples = {
"ime123": [{"id": 145,
"desig": "doctor",
"name": "Manu",
"place": "ABCD"
}],
"ime148": [{"id": 148,
"desig": "engineer",
"name": "John",
"place": "POLK"
},
{
"id": 150,
"desig": "scientist",
"name": "Mary",
"place": "USE"
}]
};
$scope.mytable = new ngTableParams({
sorting: {
name: 'desc'
}
}, {
getData: function($defer, params) {
$scope.peoples = $filter('orderBy')( $scope.peoples, params.orderBy());
$defer.resolve( $scope.peoples);
}
});
});
The way you work with nested array in ngtable is not suitable ,in your case you can make array one dim again and allow directive to groupping
html
<table border="1" ng-table="mytable">
<tbody ng-repeat="peop in $groups">
<tr ng-repeat="people in peop.data">
<td sortable="id" data-title="'Id'">{{people.id}}</td>
<td sortable="desig" data-title="'Desig'">{{people.desig}}</td>
<td sortable="name" data-title="'Name'">{{people.name}}</td>
<td sortable="place" data-title="'Place'">{{people.place}}</td>
</tr>
</tbody>
</table>
contoller
$scope.mytable = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'desc'
}
}, {
total: peoples.length,
groupBy:'group',
getData: function ($defer, params) {
peoples = $filter('orderBy')(peoples, params.orderBy());
$defer.resolve(peoples);
}
});
data
var peoples = [{
"id": 145,
"desig": "doctor",
"name": "Manu",
"place": "ABCD",
"group": "ime123" //for grouping
}, {
"id": 148,
"desig": "engineer",
"name": "John",
"place": "POLK",
"group": "ime148" //for grouping
}, {
"id": 150,
"desig": "scientist",
"name": "Mary",
"place": "USE",
"group": "ime148" //for grouping
}];
here almost working jsfiddle.
default desc not working yet (ver 0.3.1)

Unable to Bind Json to TreeTable Js using knockout.js

I am using the TreeTable plugin:
http://ludo.cubicphuse.nl/jquery-treetable/#examples
<table id="example-basic">
<thead>
<tr>
<th>Name</th> <th>Status</th> <th>id</th>
</tr>
</thead>
<tbody data-bind="foreach: TreeView">
<tr data-bind="attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}">
<td data-bind="text: Name"></td>
<td data-bind="text: Status"></td>
<td data-bind="text: id"></td>
</tr>
</tbody>
</table>
<button type="button" name="test" onclick="test()"></button>
The below works if I HardCode as is and the result is shown as a nicely formatted TreeView.
ko.applyBindings({ TreeView: [{ "id": "1", "Parentid": null, "Name": "test1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "test2", "Status": "OK" }] }
But, I am getting the value from the server(put the value obtained from server in "str" variable) and doing the binding as below:
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]',
json = JSON.stringify(eval("(" + str + ")")),
ko.applyBindings({ TreeView: json})
function reload() {
//ko.applyBindings({ TreeView: {} });
str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }]'
json = JSON.parse(str),
ko.applyBindings({ TreeView: json})
I get the following error:
Error: Unable to parse bindings.
Message: ReferenceError: 'id' is undefined;
Bindings value: attr: { 'data-tt-id': id ,'data-tt-parent-id': Parentid}
Can someone please help. Thanks!
The Json object returned had to be converted to type string and then parsed. This resolved the above issue
New Issue:
I was just playing around with the treetable plugin. I wish to reload the data from server on button click(or ajax call every 5 sec). The data is duplicated.
You are stringifying the JSON instead of parsing it, and using eval() when you don't need it. Instead, just use JSON.parse().
var str = '[{ "id": "1", "Parentid": null, "Name": "parent1", "Status": "OK" }, { "id": "2", "Parentid": 1, "Name": "child1", "Status": "OK" }]';
var json = JSON.parse(str);
ko.applyBindings({ TreeView: json });

Categories