i have added a functionality to parse a CSV file in javascript. I want to assign the parsed data to $scope.data.arr. Currently, the below code gives error "Uncaught ReferenceError: scope is not defined". I am newbie to AngularJS and I have followed the official angular tutorials.
The code is:
application.js
'use strict';
/* Application module */
var ddvApp = angular.module('ddvApp', ['ddvControllers']);
dataController.js
'use strict';
/*Data Controller*/
var ddvControllers = angular.module('ddvControllers', []);
ddvControllers.controller('DataController', ['$scope', function($scope){
$scope.data = {}; //created a empty data object.
}]);
read-csv.js
function handleFiles(files) {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
getAsText(files[0]);
}
else {
alert('FileReader are not supported in this browser.');
}
}
function getAsText(fileToRead) {
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
scope.data.arr = processData(csv); //this is the line of code where i want to assign the parsed data to the angularjs $scope.
}
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
for (var i = 0; i < allTextLines.length; i++) {
var data = allTextLines[i].split(',');
var arr = [];
for (var j = 0; j < data.length; j++) {
arr.push(data[j].trim());
}
lines.push(arr);
}
return lines;
}
function errorHandler(event) {
if(event.target.error.name == "NotReadableError") {
alert("Cannot read file !");
}
}
--UPDATE Problem Statement.
The handleFiles() function is called whenever user selects a new csv file to be parsed.
html code:
<input type="file" id="csvFileInput" onchange="handleFiles(this.files)" accept=".csv">
I firstly implemented the code to parse the CSV in javascript. I am using this data to render a graph on html canvas. I wanted a functionality where the user just selects a different csv file with updated data and the graph should update itself without further inputs. I added angularjs because (in future implementations) the file and graph need to be saved to a db. Also, some data can be requested from server instead of user loading it using a csv file.
scope.data.arrto be available there? When/where is yourread-csvcode being executed? Why aren't you doing it in an angular service/factory?read-csvcode into the global scope - put it in an Angular service. In your controller, you can inject the service and then bind anonchangeevent to theinput. In that handler, call the new service method, passing the input'sfiles.