Load data from firebase to HTML table - javascript

I have a FireBase realtime DB with some data that I would like to display in HTML grid. Structure of the DB is pretty simple:
What I want to do is to have "id", "First column", "Second column", "Third column" as a column headers and data from DB to be displayed under each respective header.
This is my HTML part:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<!--Firebase SDK code below-->
<script src="/__/firebase/8.2.6/firebase-app.js"></script>
<script src="/__/firebase/8.2.6/firebase-analytics.js"></script>
<script src="/__/firebase/8.2.6/firebase-database.js"></script>
<!-- Initialize Firebase -->
<script src="/__/firebase/init.js"></script>
<script src="firebase.js"></script>
<button onClick="readData()">Load data from FB</button>
<table class="table table-striped" id="table">
<thead>
<tr>
<th>ID</th>
<th>First column</th>
<th>Second column</th>
<th>Third column</th>
</tr>
</thead>
<tbody>
</body>
</html>
JS here:
// Firebase reference
var database = firebase.database();
rootRef = database.ref('/');
itemsRef = database.ref('/Items/');
// Other vars
var pushLabels = ["id", "First column", "Second column", "Third column"];
function readData() {
itemsRef.once('value', function (snapshot) {
var arrayLen = pushLabels.length;
var childKeyArr = [];
var table = document.querySelector('#table tbody');
snapshot.forEach(function (childSnapshot) {
var childKey = childSnapshot.key;
childKeyArr.push(childKey);
});
for (var i = 0; i < childKeyArr.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < arrayLen; j++) {
cell = row.insertCell(-1);
};
};
for (var i = 0; i < childKeyArr.length + 1; i++) {
database.ref('/Items/' + i).once('value', function (snapshot) {
snapshot.forEach(function (childSnapshot) {
var noha = childSnapshot.val();
for (var i = 0; i < pushLabels.length; i++) {
cell.innerHTML = noha;
};
});
});
}
});
}
I think it's quite "overcomplex". I was able to create rows based on number of parent items in the DB (1,2,3 as shown on the DB hierarchy screenshots) and for each of the nodes I was able to retrieve the data into snapshot but I don’t know how to project it to the grid so each value is correctly displayed to it’s relevant column.
The part where I put something into cell is obviously wrong in my code - I was just testing different ways.
Any help will be appreciated! Also if there is any better solution, some library that can do that in easier way, I would be happy if you can recommend.
Thanks!!

Is there a fixed number of columns expected, or do you want to to create columns dynamically?
Are your column headers already in the html file or are you looking to make them from the keys in the database? There's column headers in your html file, yet you also have an array storing the same. They also match the keys of each child Item so it looks a little confusing.
Here's a quick example of how you could get the table body, create a new row, create the cells, add the values from the database and then add the row to the table body.
var itemsRef = firebase.database().ref().child("Items");
var tableBody = document.querySelector('#table tbody');
function readData() {
itemsRef.once('value', function (snapshot) {
snapshot.forEach(function (item_snapshot) {
//Create html elements, TRs, TD,s etc.
var row = document.createElement("tr");
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
//Add data to the new elements.
col1.innerText = item_snapshot.key;
col2.innerText = item_snapshot.child("First column").val();
col3.innerText = item_snapshot.child("Second_column").val();
col4.innerText = item_snapshot.child("Third_column").val();
//Append the cells into the row and the row into the table body.
row.appendChild(col1);
row.appendChild(col2);
row.appendChild(col3);
row.appendChild(col4);
tableBody.appendChild(row);
});
});
}
It sounds kinda like you want to have the keys of each child Item to be the column headers if I'm not misunderstanding you, but keep in mind that each child might not have the same nodes within it and you only want to load the headers once, rather than from each child Item.

Related

How to get the value of an id and that it serves to delete an element from firebase realtime database?

It is the first time I use firebase and javascript, I am making a table where it shows me the data from a database in real time. For this, I'm pulling the data like this:
function getSonido() {
var firebase = "https://iotplatform-11dca-default-rtdb.firebaseio.com/users/awsBewgkSMcqiINzOoFUiUe9D6r1/data_widget/sensor/sonido.json";
var sensores = new EventSource(firebase);
sensores.addEventListener('put', function(e) {
var json = JSON.parse(e.data);
console.log(json);
if (json.path == "/") {
tbody = document.getElementById("tbody_sonido");
for (var key in json.data) {
var tr = document.createElement("tr");
var td_sensor = document.createElement("td");
var td_sonido = document.createElement("td");
var input_sonido = document.createElement("input");
var td_ruta = document.createElement("td");
var td_button = document.createElement("td");
input_sonido.type = "number";
input_sonido.id = key;
input_sonido.readOnly = true;
input_sonido.disabled = true;
td_sensor.innerHTML = json.data[key].name;
td_ruta.innerHTML = "/" + key + "/sonido";
td_button.innerHTML = '<button class="btn btn-danger delete" id="' + key + '" type="button">Borrar</button>';
td_sonido.appendChild(input_sonido);
tr.appendChild(td_sensor);
tr.appendChild(td_sonido);
tr.appendChild(td_ruta);
tr.appendChild(td_button);
tbody.appendChild(tr);
document.getElementById(key).value = json.data[key].sonido;
}
} else {
s = json.path.split("/");
console.log(s[1]);
console.log(json.data);
document.getElementById(s[1]).value = json.data;
}
});
};
<!DOCTYPE html>
<html lang="en">
<head>
<title>Widgets</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script type="text/javascript" src="/static/js/get_sensores.js"></script>
</head>
<body>
<h1>Sound sensors</h1>
<table id="table_sonido" class="table table-striped">
<thead id="thead_sonido">
<tr>
<th>Name</th>
<th>Value</th>
<th>Route</th>
</tr>
</thead>
<tbody id="tbody_sonido">
<!-- One row will be added for each item in the json file -->
</tbody>
</table>
<script>
document.onload = getSonido();
</script>
</body>
</html>
Place a button on each item in the table that is added, all buttons have the same class but the ID value of each button will depend on the item saved in firebase, in console the button is displayed like this
I am trying to remove the element that I click to delete, for that I must get the value of the ID of the button, investigating found that I could use console.log(document.getElementsByClassName("delete")[0].id); but there I am specifying which button I want to get the value from, which is not correct.
Looking for I saw that some used the jQuery library but don't explain much the process.
While I found a solution to that first problem, I was working with the way to eliminate the element, in the documentation comes something like this curl -X DELETE \ 'https://[PROJECT_ID].firebaseio.com/locations.json' so try using something like this:
const request = new Request('https://iotplatform-11dca-default-rtdb.firebaseio.com/users/awsBewgkSMcqiINzOoFUiUe9D6r1/data_widget/sensor/sonido/0x459ece7.json', { method: 'DELETE'})
const response = await fetch(request)
return await response.json()
This would run with an onclick within a function but it also does nothing, try the same using the SDK, perform the configuration and use remove(), to remove but I also did not work and it marked me error or simply did not run.
I hope I have explained and I know that it is very extensive but I have already been several days and I have looked a lot for how to do this firebase even in videos but I just do not get the result I need and I have been trying everything for several days but I simply can not make it work.
I hope you can help me

How to call for JSON output from an API into HTML?

new to building web apps. please advise on some resources to read up if you have any good ones!
Problem:
I have created a call API on AWS - https://tnmw5vn267.execute-api.us-east-1.amazonaws.com/dev
the output is a JSON object.
However, I have no clue how to put this into a HTML page (i.e. How to get the JSON object into the HTML and then subsequently show it as a table), only:
`function CreateTableFromJSON() {
var myEmployees = [
{
"FirstName": "Benjamin",
"LastName": "Tan"
}
]
// EXTRACT VALUE FOR HTML HEADER.
// ('Book ID', 'Book Name', 'Category' and 'Price')
var col = [];
for (var i = 0; i < myEmployees.length; i++) {
for (var key in myEmployees[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < myEmployees.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myBooks[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}`
The above only generates a static table that doesn't update based on my API output. Am not sure how to do it?
Let me show you the solution.
Firstly you need to fetch JSON from API by fetch function.
After that, you need to put it to a particular HTML element by .innerHTML
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
</head>
<body>
<script>
async function fetchDataAndRenderTable() {
const serverURL = 'https://tnmw5vn267.execute-api.us-east-1.amazonaws.com/dev'
const dataFromTheServer = await fetch(serverURL).then(res => res.json())
const tableHTMLElement = document.createElement('table')
tableHTMLElement.innerHTML = `
<table style="width:100%">
<tr>
<th>FirstName</th>
<th>LastName</th>
</tr>
${
dataFromTheServer.map(item => {
return `
<tr>
<td>${item.FirstName}</td>
<td>${item.LastName}</td>
</tr>
`
})
}
</table>
`
document.body.appendChild(tableHTMLElement)
}
fetchDataAndRenderTable()
</script>
</body>
</html>
PS. But your API needs to allow CORS, otherwise you will be not able to fetch it from the browser
Here's how I might approach it using plain JS.
Use fetch to get the data from the API.
Use template literals to build up a sequence of HTML strings using map and join.
Add the final string to the page.
const json = '[{"LatestGreetingTime":"2021-06-19T15:47:10.539Z","ID":"Hello from Lambda, Benjamin Tan","FirstName":"Benjamin","LastName":"Tan"},{"LatestGreetingTime":"2021-06-19T13:44:33.761Z","ID":"Hello from Lambda, ichal shodin","FirstName":"ichal","LastName":"shodin"},{"LatestGreetingTime":"2021-06-19T13:44:33.761Z","ID":"Hello from Lambda, victoria Lovelace","FirstName":"victoria","LastName":"Lovelace"}]';
// This simulates a call to your API
function mockFetch() {
return new Promise((res, rej) => {
setTimeout(() => res(json), 1000);
});
}
// Grab the button, and a div where you can place the table
const button = document.querySelector('button');
const div = document.querySelector('div');
// Add an event listener to your button that
// callApi when it's clicked
button.addEventListener('click', callApi, false);
// As mentioned the comments you should be using
// the fetch API here, and it would look like
// fetch(url).then(res => res.json).then(buildTable)
function callApi() {
mockFetch()
.then(res => JSON.parse(res))
.then(buildTable);
}
// This function takes the data, extracts the headings
// from the first object, and then builds the row data.
// It finally puts everything together as a template literal
// and adds it to the div
function buildTable(data) {
const headings = buildHeadings(Object.keys(data[0]));
const rows = buildRows(data);
div.innerHTML = `<table><thead>${headings}</thead><tbody>${rows}</tbody></table>`;
}
// Iterate over the headings array and return heading HTML
function buildHeadings(headings) {
return headings.map(heading => `<th>${heading}</th>`).join('');
}
// Iterate over the data return row HTML
function buildRows(data) {
return data.map(row => `<tr>${buildCells(row)}</tr>`).join('');
}
// Iterate over the row data and return cell HTML
function buildCells(row) {
return Object.values(row).map(cell => `<td>${cell}</td>`).join('');
}
table { border-collapse: collapse; padding 0.2em; }
td { padding: 0.5em }
<button>Call API</button>
<div />

dynamically add radio and dropdown list in Html with JavaScript and return data back

I am creating a Google WebApp where I have collected a one dimensional array from spreadsheet.
Now the challenge Part is creating a radio button and dropdownList with the count of that array in HTML and pull the user input back into the spreadsheet.
Here is what I have done till now:-
Html --->
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<?!= include('page-css'); ?>
</head>
<body>
<form id="myform">
<table class="striped" width="100">
<thead>
<tr>
<th>Agent</th>
<th>S1</th>
<th>S2</th>
<th>S3</th>
<th>Weekoff-1</th>
<th>Weekoff-2</th>
</tr>
</thead>
<tbody id="perf"></tbody>
</table>
<input type="submit"/>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<?!= include('roster-js'); ?>
</body>
</html>
and finally where I need help JavaScript front end side:->
<script>
document.addEventListener('DOMContentLoaded', function(){
google.script.run.withSuccessHandler(getRosterData).loadRoster();
//getTable1Data(data);
});
function getRosterData(dataArray) {
let weeksArray = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
let tbody = document.getElementById("perf");
dataArray.forEach(function(ele) {
// creating row element for each agent
const tableRow = document.createElement("tr");
// create td elements
var agentTD = document.createElement("td");
agentTD.setAttribute("id", "agent"+ ele);
var t = document.createTextNode(ele);
agentTD.appendChild(t);
// create td elements with unique ids
var s1TD = document.createElement("td");
s1TD.appendChild(createRadioButton( "s1-" + ele));
// create td elements with unique ids
var s2TD = document.createElement("td");
s2TD.appendChild(createRadioButton( "s2-" + ele));
// create td elements with unique ids
var s3TD = document.createElement("td");
s3TD.appendChild(createRadioButton( "s3-" + ele));
// create td elements with unique ids
var w1TD = document.createElement("td");
w1TD.appendChild(createDropdown("w1-" + ele));
// create td elements with unique ids
var w2TD = document.createElement("td");
w2TD.appendChild(createDropdown("w2-" + ele));
// append td to table row
tableRow.appendChild(agentTD);
tableRow.appendChild(s1TD);
tableRow.appendChild(s2TD);
tableRow.appendChild(s3TD);
tableRow.appendChild(s3TD);
tableRow.appendChild(w1TD);
tableRow.appendChild(w2TD);
tbody.appendChild(tableRow);
});
function createRadioButton(id) {
//create a radio button
var radio = document.createElement("input");
radio.setAttribute("type", "radio");
radio.setAttribute("id", id);
return radio;
}
function createDropdown(id) {
//create a radio button
var fragment = document.createDocumentFragment();
var select = document.createElement('select');
select.setAttribute("id", id);
weeksArray.forEach(function (day) {
select.options.add( new Option(day, day));
});
fragment.appendChild(select);
return fragment;
}
document.getElementById("myform")
}
</script>
This Question has gone too big. Anyways now I need help to populate a html page with the list of names that I have collected from Google Spreadsheet and Simultaneously add 3 radio buttons and a drop-down list respectively. At the end capture data if user submits form.
Please let me know if anymore clarification is required.
Here is the outcome by now :-
This can be done using Document Fragments. you can read more about it here:
Document Fragments
For e.g to create list:
function getRosterData(dataArray) {
let tbody = document.getElementById('perf');
var fragment = document.createDocumentFragment(),
select = document.createElement('select');
dataArray.forEach(function(r) {
select.addChild(r, r);
}
}
Options is used to create options for the dropdown list.
Similarly, you can use document.createElement() to create radio buttons with some unique id's which you can later use to capture data when they submit it.
Codepen: i have created a small codepen to help out with it:
It can be view here Codepen Link

Sorting Auto Generated JSON Table (JSON Taken From Fetch Data) Not Working

In my off time I've been messing around with API's but now I want to create a sortable table with the JSON information returned from the API call.
I found some code online to help me grab the JSON response and make it into a dynamically generated table, which displays just fine. However, when I try to sort it, it wont work. I've tried tablesorter, datatable and sortable.
Right now, I'm just trying to make it work with Sortable but I believe if it works with Sortable, it will work with the rest.
Also, for clarity sake on Sortable, it works in this code on the line where I set the table attribute:
table.setAttribute('data-sortable', '');
I have also tested it on another hard-coded table just in case, and it works. It can be found here.
Here is my code - Or if you want to view it more clearly, I created a jsFiddle for it here
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sortable/0.8.0/css/sortable-theme-minimal.css" />
</head>
<body>
<div id="showData"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sortable/0.8.0/js/sortable.js"></script>
<script>
url = 'https://jsonplaceholder.typicode.com/posts';
function foo() {
// RETURN the promise
return fetch(url).then(function(response) {
return response.json(); // process it inside the `then`
});
}
foo().then(function(response) {
// access the value inside the `then`
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < response.length; i++) {
for (var key in response[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var container = document.getElementById('showData');
var table = document.createElement('table');
table.setAttribute('data-sortable', '');
container.appendChild(table);
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
var thead = document.createElement("thead");
table.appendChild(thead);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
thead.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < response.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = response[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
})
</script>
</body>
</html>
According to the docs:
If you add tables with JavaScript, call init after they are added to
the page:
Sortable.init()
As you are dynamically generating the table, you need to call Sortable.init() after everything is ready in the DOM.

Javascript/for loop/HTML table positioning

Description of program:
-My program uses a javascript for loop to place the data from an external javascript array named "arrays.js" into an HTML table. This program is suposed to place the correct data under the "Date Name Address Amount" table headings.
Problem:
-The data in the array is overstepping its boundarys or I should say lack of boundaries set within the table headers "Date Name Address Amount" Its not creating a new record after the "Amount" header, its simply adding the new record to the same line.I would like it to wrap back around to the next record row starting under "Date" table header. so that the dates value in the arrya will be under the "date" header, name value under the "Name" header...etc example bellow....
Example: I have 4 headers (Date, Name, Address, Amount) I would like the start of the next date under the next array to be placed under the "Date" table header.It placing the next date value of the array on the same row its not wraping around to a new record row. Code is bellow.
Date Name Address Amount
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Winch - Lab 10</title>
<script src="arrays.js" type="text/javascript"></script>
<script type="text/javascript">
function totalContributions()
{
var totalAmount = 0;
for (var i = 0; i < amount.length; i++)
totalAmount = totalAmount + amount[i];
return totalAmount;
}
</script>
</head>
<body>
<table id="donations">
<tr>
<th>Date</th>
<th>Name</th>
<th>Address</th>
<th>Amount</th>
</tr>
<script>
for (var x=0; x < amount.length; x++){
if (x%2==0){
document.write("<tr>");
} else {
document.write("<tr class='stripe'>");
}
document.write("<td>"+date[x]+"</td>");
document.write("<td>"+firstName[x]+" "+lastName[x]+"</td>");
document.write("<td>"+street[x]+"<br>"+city[x]+","+state[x]+" "+zip[x]);
document.write("<td class='amt'>$"+amount[x]+"</td>");
document.write("</tr)");
}
</script>
</table>
</body>
</html>
**arrays.js**
street = new Array();
city = new Array();
state= new Array();
zip = new Array();
amount = new Array();
date = new Array();
firstName[0]="Ron";
lastName[0]="Burgundy";
street[0]="88 Regal Lane";
city[0]="Williamsburg";
state[0]="KY";
zip[0]="40769";
amount[0]=625;
date[0]="2015-07-18";
firstName[1]="Ricky";
lastName[1]="Bobby";
street[1]="407 Easy Street";
city[1]="London";
state[1]="KY";
zip[1]="40744";
amount[1]=75;
date[1]="2015-07-18";
firstName[2]="Veronica";
lastName[2]="Corningstone";
street[2]="743 Stawlings Drive";
city[2]="Danville";
state[2]="KY";
zip[2]="40423";
amount[2]=50;
date[2]="2015-07-16";
firstName[3]="Brick";
lastName[3]="Tamland";
street[3]="102 Maple Lane";
city[3]="Danville";
state[3]="KY";
zip[3]="40423";
amount[3]=150;
date[3]="2015-07-15";
1) You forgot to define firstName and lastName variables in arrays.js file.
2) Inside for-loop the tr tag is not closed, changed document.write("</tr)"); to document.write("</tr>");.
Working Code:
Html Code:
`
Winch - Lab 10
function totalContributions()
{
var totalAmount = 0;
for (var i = 0; i < amount.length; i++)
totalAmount = totalAmount + amount[i];
return totalAmount;
}
</script>
</head>
<body>
<table id="donations" style="width:100%;" border="1">
<tr>
<th>Date</th>
<th>Name</th>
<th>Address</th>
<th>Amount</th>
</tr>
<script>
for (var x=0; x < amount.length; x++){
if (x%2==0){
document.write("<tr>");
} else {
document.write("<tr class='stripe'>");
}
document.write("<td>"+date[x]+"</td>");
document.write("<td>"+firstName[x]+" "+lastName[x]+"</td>");
document.write("<td>"+street[x]+"<br>"+city[x]+","+state[x]+" "+zip[x]);
document.write("<td class='amt'>$"+amount[x]+"</td>");
document.write("</tr>");
}
</script>
</table>
</body>
</html>
arrays.js
street = new Array();
city = new Array();
state= new Array();
zip = new Array();
amount = new Array();
date = new Array();
firstName = new Array();
lastName = new Array();
firstName[0]="Ron";
lastName[0]="Burgundy";
street[0]="88 Regal Lane";
city[0]="Williamsburg";
state[0]="KY";
zip[0]="40769";
amount[0]=625;
date[0]="2015-07-18";
firstName[1]="Ricky";
lastName[1]="Bobby";
street[1]="407 Easy Street";
city[1]="London";
state[1]="KY";
zip[1]="40744";
amount[1]=75;
date[1]="2015-07-18";
firstName[2]="Veronica";
lastName[2]="Corningstone";
street[2]="743 Stawlings Drive";
city[2]="Danville";
state[2]="KY";
zip[2]="40423";
amount[2]=50;
date[2]="2015-07-16";
firstName[3]="Brick";
lastName[3]="Tamland";
street[3]="102 Maple Lane";
city[3]="Danville";
state[3]="KY";
zip[3]="40423";
amount[3]=150;
date[3]="2015-07-15";
The world is moving to Angular, and I would recommend you to do same.
In Angular way, you can do this using either the angular-data-table or using the angular-material-data-table.
angular-data-table works fine with 1.5.8 but will not be supported in
angular2
angular material-data-table (md-data-table) works with 1.5.8
and will be supported in angular2 too.
Below is an example of md-data-table
<mdt-table table-card="{visible: true, title: 'Donations'}" paginated-rows = "true">
<mdt-header-row>
<mdt-column align-rule="left"><b>Name</b></mdt-column>
<mdt-column align-rule="left"><b>Description</b></mdt-column>
<mdt-column align-rule="left"><b>Since Year</b></mdt-column>
</mdt-header-row>
<mdt-row ng-repeat="item in donations">
<mdt-cell>{{item.name}}</mdt-cell>
<mdt-cell>{{item.description}}</mdt-cell>
<mdt-cell>{{item.since_yr}}</mdt-cell>
</mdt-row>
</mdt-table>
The above code also does pagination for you. Awesome!
The above code can also be used to make rows selectable by putting in :
selectable-rows="true" in
What u have to do is:-
write a angular module using ng-app and that can be included in ur body tag or create a parent tag on top of above code.
write a controller to move ur logic into the controller.
Below is an example.
angular.module('testModule',[])
.controller('testController', function($scope){
$scope.donations = function (){
//Your logic for donations goes here.
};
});

Categories