简体   繁体   中英

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?

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>

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 it can helps someone.

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); }; $scope.upload = function(file){ console.log(file); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM