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?
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>
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With