Reputation: 385
I am trying to run my upload()
function when a file input changes. However, I can't make it work.
HTML:
<input type="file" ng-model="image" ng-change="uploadImage()">
JS:
$scope.uploadImage = function() {
console.log('Changed');
}
What am I doing wrong?
Upvotes: 17
Views: 64775
Reputation: 1305
Another interesting way to listen to file input change is with a watch over the ng-model attribute of the input file.
Like this:
HTML -> <input type="file" file-model="change.fnEvidence">
JS Code ->
$scope.$watch('change.fnEvidence', function() {
alert("has changed");
});
Hope this helps.
Upvotes: 3
Reputation: 12263
Here's a directive I made that accomplishes what you are asking. If I'm not mistaken, I think the other solutions won't work in production mode, but this one does. It is used like so:
<input ng-upload-change="fileChanged($event)" />
In your controller:
$scope.fileChanged = function($event){
var files = $event.target.files;
}
And for the directive to include somewhere in your code:
angular.module("YOUR_APP_NAME").directive("ngUploadChange",function(){
return{
scope:{
ngUploadChange:"&"
},
link:function($scope, $element, $attrs){
$element.on("change",function(event){
$scope.$apply(function(){
$scope.ngUploadChange({$event: event})
})
})
$scope.$on("$destroy",function(){
$element.off();
});
}
}
});
This code is released into the public domain, no attributions required.
You should also be aware that if somebody selects a file, closes the file input, and then selects the same file again later on, it won't fire the change function again. To fix this, I've created a more complete directive that replaces the input under the hood each time you use it. I put it on github here:
https://github.com/dtruel/angular-file-input/tree/master
Upvotes: 53
Reputation: 1
Use ng-file-select="upload($files)"
'<input type="file" class="form-control" ng-model="alunos.file" accept="image/*" ng-file-select="upload($files)"/>'
where upload is a function:$scope.upload = function(file){
console.log(file);
};
Upvotes: -5
Reputation: 9612
JS:-
function myCtrl($scope) {
$scope.uploadImage = function () {
console.log("Changed");
}
}
HTML:-
<div ng-app ng-controller="myCtrl">
<input type="file" ng-model="image" onchange="angular.element(this).scope().uploadImage()" />
</div>
Upvotes: 54