Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-change on <input type="file"

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?

like image 475
Pixark Avatar asked Nov 22 '13 14:11

Pixark


3 Answers

Try this out:- http://jsfiddle.net/adiioo7/fA968/

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>
like image 152
Aditya Singh Avatar answered Nov 03 '22 23:11

Aditya Singh


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

like image 45
user3413723 Avatar answered Nov 04 '22 00:11

user3413723


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.

like image 35
halbano Avatar answered Nov 03 '22 23:11

halbano