Upload Function in AngularJs requires to be double clicked to display table - javascript

I am uploading and displaying a csv file using angular. The Upload button/function takes care of reading and parsing the csv so the html can display. However, the table is not displaying the with the initial click, it requires a second click of the upload button to display. When I log in console, it shows that the array of objects is created after the first click.
vm.upload = function () {
var fileUpload = document.getElementById("fileUpload");
var reader = new FileReader();
reader.onload = function (e) {
var lines = e.target.result.split("\n");
var result = [];
var headers = lines[0].split(',');
for(var i = 1;i<lines.length;i++){
var obj = {};
var currentline = lines[i].split(',');
for(var j = 0;j < headers.length; j++){
obj[headers[j]] = currentline[j];
}
if (obj[headers[1]] == undefined){
continue;
}
result.push(obj);
}
vm.head = headers;
vm.data = result;
console.log(result);
console.log(headers)
console.log(vm.data)
}
reader.readAsText(fileUpload.files[0]);
vm.editTable = false
vm.display = true;
};

Because your scope changes are not happening as a direct (i.e. non-async) result of a user interaction, you probably been to use $scope.$apply to trigger a UI update.
Jim Hoskins has a good blog post about this:
Jim's Blog

Related

Input File Processing

I have a piece of code that is working....it allows me to display multiple files in a list when a user clicks on Choose File. The code works fine. However, I am trying to figure out if it's possible to append to the list instead of creating a new one each time. I've researched this most of the afternoon and a vast majority of the articles say it's not easily done. Should I be using a FormData approach instead? Would that buy me anything?
Here is my Javascript code...It works fine...
window.onload = function() {
const inputElement = document.getElementById("my_files");
const fileNames = document.getElementById("file_names");
let fileList = [];
function removeFile(event) {
event.preventDefault();
let filename = this.dataset.filename;
let modifiedFileList = new DataTransfer();
for (let i = 0; i < fileList.length; i++) {
if (fileList[i].name !== filename) {
modifiedFileList.items.add(fileList[i]);
}
}
inputElement.files = modifiedFileList.files;
fileList = inputElement.files;
handleFiles(fileList);
return false;
}
inputElement.addEventListener("change", handleFilesListener, false);
function handleFilesListener() {
fileList = this.files;
handleFiles(fileList);
}
function handleFiles(fileList) {
fileNames.textContent = '';
for (let i = 0; i < fileList.length; i++) {
let listElement = document.createElement("li");
let textNode = document.createTextNode(fileList[i].name);
listElement.appendChild(textNode);
listElement.setAttribute("class","attachmentname");
let removeButton = document.createElement("button");
removeButton.innerHTML = "Remove&nbsp";
removeButton.setAttribute('type', 'button')
removeButton.setAttribute("class", "button121");
removeButton.setAttribute('data-filename', fileList[i].name)
removeButton.addEventListener('click', removeFile)
listElement.appendChild(removeButton);
fileNames.appendChild(listElement);
}
}
}
Again, I'm trying to figure out if I can append to this list instead of constantly looping through it if the list changes. I did try to do an append instead of add below...but that didn't work. I'm a self proclaimed newb...so please go easy on me. :).
let filename = this.dataset.filename;
let modifiedFileList = new DataTransfer();
for (let i = 0; i < fileList.length; i++) {
if (fileList[i].name !== filename) {
modifiedFileList.items.add(fileList[i]);
}
}
Thanks in advance for any pointers.

save the data in localstorage with JSON

I made some test code, but it doesn't work what I want.
I push the data on localstorage, and get the data from localstorage. After that, I changed the value of data, and push and add the data on localsorage. Then, I checked the data and I was trying to get data with JSON.parse function. However, it didn't work.
Here's a code
var temp1 = {
'temp1': true,
'test1': true
};
var temp2 = {
'temp2': true,
'test2': true
};
var temp3 = [];
temp3.push(temp1);
localStorage.setItem("testing", JSON.stringify(temp3));
var temp4 = localStorage.getItem("testing");
var temp5 = JSON.parse(temp4);
for(var i=0; i<temp5.length; i++)
{
temp5[i].temp1 = false;
}
temp3.push(temp5);
localStorage.setItem("testing", JSON.stringify(temp3));
var temp6 = localStorage.getItem("testing"));
var temp7 = JSON.parse(temp6);
for(var j=0; j<temp7.length; i++)
{
temp7[i].test1 = false;
}
temp3.push(temp7);
localStorage.setItem("testing", JSON.stringify(temp3));
There are a couple of minor syntax errors as mentioed by si2zle, however the main issue is that when you are pushing temp5 and temp7 to temp3, you are actually pushing a new array instead of the individual elements.
You need to push each individual element to temp3 inside the for loop like so
for(var i=0; i<temp5.length; i++)
{
temp5[i].temp1 = false;
temp3.push(temp5[i]);
}
There was an error in the following code:
for(var j=0; j<temp7.length; i++)
{
temp7[i].test1 = false;
}
it was j++ not i++ and temp7[j].test1 = false; not temp7[i]
There is an extra ')' at var temp6 = localStorage.getItem("testing"));
also, while "temp3.push(temp5);" it pushes array in an array
like this: [{"temp1":true,"test1":true},[{"temp1":false,"test1":true}]]
which creates problem while parsing in the for loop.
for(var j=0; j<temp7.length; i++)
{
temp7[i].test1 = false;
}
Hope this helps:)

localStorage is not updating edited information

I have problem editing local storage data. I saved Array of Array-list in local storage and it works, or save. However, when i tried to edit, it only edit temporarily and the edited data disappear when i refresh the page and it shows the original data i saved
function editinfo(){
var name = document.getElementById("nameB").value;
var price = document.getElementById("priceB").value;
var quant = document.getElementById("quantityB").value;
var retrieved = window.localStorage.getItem("done");
var pro = JSON.parse(retrieved);
for (i = 0; i < pro.length; ++i){
if(pro[i][0] === name){
pro[i][1]= price
pro[i][2] = quant;
} else{
console.log("There is no such data to edit");
}
}
window.localStorage.setItem("done", JSON.stringify(pro));
}
// I saved information on local storage, I read data from server.
var bevInventory = $.getJSON('http://pub.jamaica-inn.net/fpdb/api.php?username=jorass&password=jorass&action=inventory_get');
function Info(){
var info = [];
bevInventory.done(function(result){
for(i = 0; i < result.payload.length; ++i){
if(result.payload[i].namn != ""){
var makeList = [result.payload[i].namn, result.payload[i].price, result.payload[i].count];
info.push(makeList);
}
}
var xx = window.localStorage.setItem("done", JSON.stringify(info));
})
return info;
}
One solution is to check first, and add data to local storage if it does not exist. Like this
function editinfo() {
var name = 'bob';
var price = 1;
var quant = 2; // loaded dynamically from page.
if (window.localStorage.hasOwnProperty("done")) {
var retrieved = window.localStorage.getItem("done");
var pro = JSON.parse(retrieved);
for(i = 0; i < pro.length; ++i){
if(pro[i][0] === name){
pro[i][1] = price
pro[i][2] = quant;
}
}
} else {
pro = [[name, price, quant]];
}
window.localStorage.setItem("done", JSON.stringify(pro));
}
Your code fails if there is no "done" data initially in localStorage. JSON.parse() parses null (because of no data) and then error occurs on line
pro.length
So it's better to check if it's a first launch and there is no data:
if (!pro) {
pro = [];
}
Example here
After first executing of editinfo() data successfully saves in localStorage.

Google Apps Script: How to get this code run after UI is closed?

This may seem a very newbie question, but I'm stuck with it. I've got this code to show a check list in a UI and insert the paragraphs of one or more documents into another target document:
var fact_list = [ ["Kennedy Inauguration", "politics", "tZwnNdFNkNklYc3pVUzZINUV4eUtWVWFSVEf"], ["Pericles’ Funeral Oration", "politics", "sdgrewaNkNklYc3pVUzZINUV4eUtW345ufaZ"], ["The Pleasure of Books", "culture", "1234rFszdgrfYc3pVUzZINUV4eU43usacd"], ["I Am The First Accused (Nelson Mandela)", "law", "34rsgadOsidjSZIswjadi95uydnfklsdks"] ];
function showList() {
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication();
var panel = app.createVerticalPanel().setId('panel');
// Store the number of items in the array (fact_list)
panel.add(app.createHidden('checkbox_total', fact_list.length));
// add 1 checkbox + 1 hidden field per item
for(var i = 0; i < fact_list.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(fact_list[i][0]);
var hidden = app.createHidden('checkbox_value_'+i, fact_list[i]);
panel.add(checkbox).add(hidden);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
app.add(panel);
mydoc.show(app);
}
function submit(e){
var numberOfItems = e.parameter.checkbox_total;
var itemsSelected = [];
// for each item, if it is checked / selected, add it to itemsSelected
for(var i = 0; i < numberOfItems; i++){
if(e.parameter['checkbox_isChecked_'+i] == 'true'){
itemsSelected.push(e.parameter['checkbox_value_'+i]);
}
}
var app = UiApp.getActiveApplication();
ScriptProperties.setProperties({'theses': itemsSelected}, true);
app.close();
return app;
}
function importTheses(targetDocId, thesesId, thesesType) { // adapted from Serge insas
var targetDoc = DocumentApp.openById(targetDocId);
var targetDocParagraphs = targetDoc.getParagraphs();
var targetDocElements = targetDocParagraphs.getNumChildren();
var thesesDoc = DocumentApp.openById(thesesId);
var thesesParagraphs = thesesDoc.getParagraphs();
var thesesElements = thesesDoc.getNumChildren();
var eltargetDoc=[];
var elTheses=[];
for( var j = 0; j < targetDocElements; ++j ) {
var targetDocElement = targetDoc.getChild(j);
// Logger.log(j + " : " + type);// to see targetDoc's content
eltargetDoc[j]=targetDocElement.getText();
if(el[j]== thesesType){
for( var k = 0; k < thesesParagraphs-1; ++k ) {
var thesesElement = thesesDoc.getChild(k);
elTheses[k] = thesesDoc.getText();
targetDoc.insertParagraph(j, elTheses[k]);
}
}
}
}
But when I call these functions inside my main function, I got a red message (in my language): service not available: Docs and, after the UI from showList() is closed, nothing more happens with my code (but I wanted the main functions continues to run). I call these functions this way:
if (theses == 1){
showList();
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
}
showURL(docName, link); // Shows document name and link in UI
So, how can I fix that? How can I get the code run until the line showURL(docName, link);?
showList();
This function creates only Ui.
You are setting the script properties only in the Server Handler which executes on the click of submit button. Since then:
ScriptProperties.getProperty('theses');
will hold nothing. So you need to call these lines:
var thesesArrays = ScriptProperties.getProperty('theses');
for (var i = 0; i < thesesArrays.lenght(); i++){
var thesesId = ScriptProperties.getProperty('theses')[i][2];
var thesesType = ScriptProperties.getProperty('theses')[i][1];
importTheses(target, thesesId, thesesType);
}
Inside server handler or put them inside a method and call the method from the server Handler.

sharepoint javascript on click shape

I need to add an onclick event to shapes from Visio in SharePoint, with JavaScript, like the vwaControl handler shapeselectionchanged but on click, is there any way I could do that?
I'm sorry about my English is not my native language.
I hope you can understand me.
I just did something similar.
You can use the shapeSelectionChangedHandler to handle clicks to. As far as I know there is no onClick functionality, but shapeSelectionChangedHandler works fine for me.
See:
Programming with Visio in SharePoint, create new Outlook meeting in ?Javascript?
See: http://msdn.microsoft.com/en-us/library/gg243427.aspx for guide to set it up with Content WebPart and so on.
Code I use, just add what you want in shapeSelectionChangedHandler = function(source, args) {}
<script language="javascript">
var app = Sys.Application;
app.add_load(onApplicationLoad);
// hold an instance of the Visio VWA control
var vwaControl;
var shapeSelectionChangedHandler = null;
function onApplicationLoad()
{
vwaControl= new Vwa.VwaControl("WebPartWPQ4");
vwaControl.addHandler("diagramcomplete", onDiagramComplete);
vwaControl.addHandler("shapeselectionchanged", shapeSelectionChangedHandler);
}
function onDiagramComplete()
{
var vwaPage = vwaControl.getActivePage();
vwaPage.setZoom(35); // force the initial zoom level
}
shapeSelectionChangedHandler = function(source, args)
{
// get the selected shape from the shapes on the page
var vwaPage = vwaControl.getActivePage();
var vwaShapes = vwaPage.getShapes();
var shape = vwaShapes.getItemById(args);
// get the data to display for the selected shape
var data = shape.getShapeData();
var strRoomName = "";
var strFloorNumber = "";
var strCapacity = "";
var strStatus = "";
for (var j = 0; j < data.length; j++)
{
if (data[j].label == "RoomName")
{
strRoomName = data[j].value;
continue;
}
if (data[j].label == "FloorNumber")
{
strFloorNumber = data[j].value;
continue;
}
if (data[j].label == "Capacity")
{
strCapacity = data[j].value;
continue;
}
if (data[j].label == "RoomStatus")
{
strStatus = data[j].value;
continue;
}
}
// get the selected state input and set its value
var inputRoomName = document.getElementById('strRoomName');
inputRoomName.value = strRoomName;
var inputFloorNumber = document.getElementById('strFloorNumber');
inputFloorNumber.value = strFloorNumber;
var inputCapacity = document.getElementById('strCapacity');
inputCapacity.value = strCapacity;
var inputStatus = document.getElementById('strStatus');
inputStatus.value = strStatus;
}

Categories

Resources