1

Int the following code the file object is printing as undefined why?

Html

<input  type="file" name="issueFile" file-model="jsfile"> 
<a class="btn pull-right" ng-click="create()">Create</a>  

controller

$scope.cancel = function () {
  var fd = new FormData();
  angular.forEach($scope.jsfile,function(file){
                fd.append('file',file);
 });
  fd.append('formdata',JSON.stringify(jsondata));
            $http.post('admin/managecuisineAdd',fd,{
                transformRequest:angular.identity,
                 headers:{'Content-type':undefined}
             }).success(function(data){
                 $scope.status=data;
                 $scope.itemlist.push(data)
                 $scope.message="New Dish Added Successfully"
  });
}
1
  • Is there any reason you are using a local var instead of just using $scope.myFile? Commented Jul 16, 2015 at 12:58

2 Answers 2

2

As far as I know there is no support for input[type="file"] binding.

I use a custom directive triggering the change event and filling a variable.

.directive('ngFileSelect', [ '$parse', '$timeout', function($parse, $timeout) {
    return function(scope, elem, attr) {
            var fn = $parse(attr['ngFileSelect']);
            elem.bind('change', function(evt) {
                var files = [], fileList, i;
                fileList = evt.target.files;
                if (fileList != null) {
                    for (i = 0; i < fileList.length; i++) {
                        files.push(fileList.item(i));
                    }
                }
                $timeout(function() {
                    fn(scope, {
                        $files : files,
                        $event : evt
                    });
                });
            });
        };
    }])

In my HTML I use it like this :

<input ng-file-select="onFileSelect($files)" type="file">

And in my controller :

$scope.onFileSelect = function (files) {
     console.info('files', files);
};
Sign up to request clarification or add additional context in comments.

Comments

0

Angular won't bind to file inputs out of the box. You could try some ugly hack like this:

<input type="file" multiple onchange="angular.element(this).scope().fileNameChanged(this)">

Or use a directive like this https://github.com/danialfarid/ng-file-upload

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.