有以下代码:
handleFileSelect = (evt) ->
console.log(1)
file = evt.currentTarget.files[0]
reader = new FileReader()
reader.onload = (evt) ->
$scope.$apply ($scope) ->
$scope.myImage = evt.target.result
reader.readAsDataURL(file)
angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect)
和HTML:
<div class="form-group ng-scope">
<label class="col-sm-2 control-label" for="image">Image:</label>
<div class="col-sm-10">
<div class="cropFile">
<input id="fileInput" type="file">
</div>
</div>
</div>
我想在#fileInput
中更改某个文件后,在控制台中获得'1'。但是当我选择文件时,我什么也得不到。我该如何解决?谢谢!
答案 0 :(得分:5)
通过制定指令来做到这一点。
我创建了一个指令名称上传
HTML PART
<div><input style="margin: 0 auto;" type="file" id="fileInput" upload></div>
JS for Directive
myapp.directive('upload', function($rootScope) {
return {
restrict: 'EA',
link: function(scope, elem, attrs) {
elem.on("change" ,function(evt) {
var file = evt.currentTarget.files[0];
var reader = new FileReader();
reader.onload = function(evt) {
scope.$apply(function($scope) {
$rootScope.myImage = evt.target.result;
console.log($rootScope.myImage);
});
};
reader.readAsDataURL(file);
});
}
};
});