Practical AngularJS Part 1 - Sample 1
An example of DOM manipulation by hand...
by Dave Kerr
HTML
<h3>Speedmonitor</h3>
<form id="addUrlForm">
<label for="url">Url</label>
<input id="url" type="text" />
<input id="submit" type="submit" />
</form>
<table id="urlTable">
<tr>
<td>Url</td>
<td>Load Speed (ms)</td>
<td></td>
</tr>
</table>
JavaScript
// In this array, we'll keep track of the urls and their last fetch time.
var urls = [
{url: "www.google.com", loadSpeed: 50},
{url: "angularjs.org", loadSpeed: 75},
{url: "www.dwmkerr.com", loadSpeed: 120}
];
// This function will update the url table, making sure we've got the urls..
function updateUrlTable() {
// Get the table.
var table = document.getElementById("urlTable");
// Clear old table rows, but not the heading...
var rows = table.rows.length - 1;
for(var i=0; i<rows; i++) {
table.deleteRow(1);
}
// Now add a row for each entry.
for(i=0; i<urls.length; i++) {
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = urls[i].url;
cell2.innerHTML = urls[i].loadSpeed + " ms";
cell3.innerHTML = '<a href="javascript:void(0)" onclick="removeUrl(' + i + ');">Delete</a">';
}
}
// This function deletes a row. It's added on the window as we're in an onload...
function removeUrl(index) {
// Remove the url by index.
urls.splice(index, 1);
// Update the table.
updateUrlTable();
}
// This function adds an url.
function addUrl(url) {
// Add a new url entry.
urls.push({
url: url,
loadSpeed: Math.random()*75+50
});
// Update the table.
updateUrlTable();
}
// When the form is submitted, add the url.
var form = document.getElementById("addUrlForm");
form.onsubmit = function() {
addUrl(document.getElementById("url").value);
return false;
};
// First time through, update the table.
updateUrlTable();