[英]how to access angular $scope from a javascript function
i have added a functionality to parse a CSV file in javascript. 我添加了在javascript中解析CSV文件的功能。 I want to assign the parsed data to $scope.data.arr.
我想将已解析的数据分配给$ scope.data.arr。 Currently, the below code gives error " Uncaught ReferenceError: scope is not defined ".
当前,以下代码给出错误“ Uncaught ReferenceError:范围未定义 ”。 I am newbie to AngularJS and I have followed the official angular tutorials.
我是AngularJS的新手,并且已经关注过官方的angular教程。
The code is: 代码是:
application.js 的application.js
'use strict';
/* Application module */
var ddvApp = angular.module('ddvApp', ['ddvControllers']);
dataController.js 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 读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. --UPDATE问题陈述。
The handleFiles() function is called whenever user selects a new csv file to be parsed. 每当用户选择要解析的新csv文件时,都会调用handleFiles()函数。
html code: html代码:
<input type="file" id="csvFileInput" onchange="handleFiles(this.files)" accept=".csv">
I firstly implemented the code to parse the CSV in javascript. 我首先实现了用javascript解析CSV的代码。 I am using this data to render a graph on html canvas.
我正在使用此数据在html画布上呈现图形。 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.
我想要一种功能,用户只需选择具有更新数据的其他csv文件,图形就可以自行更新而无需其他输入。 I added angularjs because (in future implementations) the file and graph need to be saved to a db.
我添加了angularjs,因为(在将来的实现中)文件和图形需要保存到db中。 Also, some data can be requested from server instead of user loading it using a csv file.
另外,可以从服务器请求一些数据,而不用用户使用csv文件加载它们。
While you can get acccess to the $scope
via angular's element()
function it looks like this is code that would be better put into an angular service
. 虽然您可以通过angular的
element()
函数访问$scope
,但看起来这是可以更好地放入angular service
。
If doing that is for some reason not an option, you need a reference to a DOM element that belongs to your controller
. 如果出于某种原因而不是这样做,则需要引用属于
controller
的DOM元素。
Once you have that, you can do 一旦有了,就可以做
angular.element(myDomElement).scope()
and that should give you a reference. 这应该为您提供参考。
You can also use element.find()
with css selectors but be aware that if you have not loaded JQuery
you're left with a limited set of selectors (tag-names only). 您还可以将css选择器与
element.find()
一起使用,但要注意,如果您尚未加载JQuery
,则剩下的是有限的选择器集(仅标记名)。
What should be done is to copy all the JavaScript from read-csv.js and put it into dataController.js below this line: 应该做的是从read-csv.js复制所有JavaScript,并将其放入以下这一行的dataController.js中:
$scope.data = {}; //created a empty data object.
define arr as an array: 将arr定义为数组:
$scope.data = {
arr: []
};
add a '$' in front of scope so that line should be: 在作用域前面添加一个“ $”,因此该行应为:
$scope.data.arr = processData(csv);
This should fix the issue. 这应该可以解决问题。
The proper way to do this is to put the functions in your read-csv.js file into a service, and then handle events using $rootScope.broadcast and $scope.$on. 正确的方法是将read-csv.js文件中的函数放入服务中,然后使用$ rootScope.broadcast和$ scope。$ on处理事件。
So it may look something like: 因此可能看起来像:
module.factory('readCsv' ['$rootScope', function(rootScope){
var readCsv = {};
// load readCsv with read-csv.js functions
readCsv.loadHandler = function(event){
var csv = readCsv.processData(event.target.result);
$rootScope.$broadcast('$csvEvent', csv);
};
return readCsv;
}]).controller('DataController', ['$scope', function($scope){
$scope.data = {};
$scope.$on('$csvEvent', function(csv){
$scope.data.arr = csv;
};
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.