AngularJs element on change event
There is the following code:
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)
And 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>
I want to get "1" in console after changing any file in #fileInput
. But when I select the file, I get nothing. How can I fix this? Thank you!
+3
source to share
1 answer
Do this by creating a directive.
I created the name of the upload directive
PART HTML
<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);
});
}
};
});
+5
source to share