无法使用angularjs
问题描述:
错误读取文本文件的内容:无法读取空
的特性“的addEventListener”我要上传从本地系统中的文件,读取它的内容,并把它传递给变量。根据业务需求,当用户点击一个按钮时,一个模式打开,在这种模式下,我必须上传文件并阅读内容。无法使用angularjs
按钮,将打开模式
<div ng-controller="CreateTestController as t_ctrl">
<button class="btn btn-primary btn-md" ng-
click="t_ctrl.importSteps()">Import Steps</button>
</div>
myApp.controller('CreateTestController', function (TestScriptApi, $scope, $modal, $rootScope) {
var t_ctrl = this;
t_ctrl.formData = {
test1: '',
test2: ''
}
/* some funationality */
// import steps added
vm.importSteps = function() {
$modal.open({
size: 'md',
templateUrl: 'js/some_location/import-step.html?',
controller: 'ImportStepController as importStepController',
resolve: {
t_ctrl: function() {
return t_ctrl;
}
}
});
};
});
进口step.html
<div >
<input type="file" name="file" id="importFile" >
<button type="button" ng-click="readFilex()">Some Button</button>
</div>
进口step.js
myApp.controller('ImportTestStepController', function ($scope, $modalInstance, t_ctrl) {
var vm = this;
vm.sequenceNo = '';
vm.command = '';
vm.method = '';
var x = document.getElementById('importFile');
x.onchange = function() {
var file = this.files[0];
alert("working");
var reader = new FileReader();
reader.onload = function (evnt) {
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for (var line = 0; line < lines.length; line++) {
// By tabs
var tabs = lines[line].split('\t');
for (var tab = 0; tab < tabs.length; tab++) {
alert(tabs[tab]);
}
}
};
reader.readAsText(file);
};
});
答
问题
getElementById
这是不如何角的作品。您不要通过Angular中的ID选择元素来添加更改侦听器。
var x = document.getElementById('importFile'); // This DOM element does not always exist. It is in an Angular template, and will be inserted in the DOM at some point.
x.onchange = function() { // Therefore, x is not defined, and you can't add .onchange on null.
这就是为什么你的错误:
无法读取空
的特性“的addEventListener”,因为x
没有定义,因为它并不总是在DOM存在。
您已经包含了角库
解决方案,使用它;不是香草的JavaScript。
<input type="file" name="file" ng-change="doSomething()" ng-model="files" >
我改变了代码,如你所说,现在我没有得到错误,但是,仍然无法读取文件。 – VivekT