我似乎无法从上传文件中获取文本字符串。在它用于我的 Controller 之前。不知何故,它停止工作并且 console.log($scope.importFile) 显示“未定义”。我对处理文件上传和 angularjs 都很陌生。您能帮忙查明出了什么问题吗?
我的指令和 Controller 以及 HTML:
app.directive('fileReader', function() {
return {
scope: {
fileReader:"="
},
link: function(scope, element) {
$(element).on('change', function(changeEvent) {
var files = changeEvent.target.files;
//console.log(files.length);
if (files.length) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
scope.$apply(function () {
scope.fileReader = contents;
});
//console.log(scope.fileReader + ' in onload');
//r.readAsText(files[0]);
};
console.log('using file-reader directive');
console.log(r.readAsText(files[0]));
r.readAsText(files[0]);
}
});
}
};
});
app.controller('NavController', function($scope, $location, $modal, toaster) {
$scope.selectFile = function () {
console.log('print upload: '+ $scope.importFile );
alert('print upload: '+ $scope.importFile);
};
};
<div class="form-group">
<input type="file" file-reader="importFile" class="form-control"/><br>
</div>
<div class="form-group">
<label>
<input class="pull-left text-left col-sm-1 control-label" type="checkbox" ng-model="confirmDeleteMode">
<span class="glyphicon glyphicon-trash col-sm-10 pull-left text-left">
<em style="color:red">By checking this box, I understand....</em>
</span>
</label>
</div>
<div class="form-group">
<input type="button" value="Upload File" class="btn btn-inverse" ng-click="selectFile()" ng-disabled="!confirmDeleteMode">
<button class="btn btn-default" type="button" ng-click="cancel()">Cancel</button>
</div>
最佳答案
首先,JavaScript 的最后一行有语法错误
app.controller('NavController', function($scope, $location, $modal, toaster) {
$scope.selectFile = function () {
console.log('print upload: '+ $scope.importFile );
alert('print upload: '+ $scope.importFile);
};
};
您忘记关闭括号的地方。 JavaScript 控制台应该通知您这一点。
app.controller('NavController', function($scope, $location, $modal, toaster) {
$scope.selectFile = function () {
console.log('print upload: '+ $scope.importFile );
alert('print upload: '+ $scope.importFile);
};
}); // <- Here
其次,虽然不重要,但 $(element)
是多余的。 AngularJS 提供了一个模仿 jQuery 的严格精简的实现,称为 jqLite。请参阅here 。这很像 jQuery,但又不完全一样。 (即使在受支持的功能中,实际上也存在显着的行为差异。因此请小心。)AngularJS 给出的所有元素都已包装在 jqLite 中。此外,如果您确实需要 jQuery,只需在 AngularJS 之前导入 jQuery,AngularJS 就会选择它并使用 jQuery 而不是 jqLite。所以这里 element
已经包装在 jQuery 中了。另一个警告是,AngularJS 2.0 将完全 drop the whole jqLite thing ,因为现在的 DOM 已经足够强大了。
否则它工作正常。请参阅Fiddle
关于javascript - angularjs FileReader 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676107/