无法使用angularjs读取文本文件的内容

时间:2017-09-05 07:15:18

标签: javascript angularjs null onchange filereader

错误:无法读取null

的属性'addEventListener'

我必须从本地系统上传文件,读取它的内容并将其传递给变量。根据业务需求,当用户点击按钮时会打开一个模态,在该模态中我必须上传文件并阅读内容。

按钮将打开模态

<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);
    };
});

1 个答案:

答案 0 :(得分:0)

<强>问题

getElementById这不是Angular的工作原理。您不要在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.

这就是您收到错误的原因:

  

无法读取null

的属性'addEventListener'

,因为x未定义,因为它并不总是存在于DOM中。

<强>解决方案

你已经包含了Angular库,使用它;不是香草javascript。

<input type="file" name="file" ng-change="doSomething()" ng-model="files" >

AngularJS documentation for ng-change

AngularJS documentation for ng-model