0

Hi Im new in angular js and I want to try get the data of my input type = "file" in my html.. But when i console it its just said undefined

html

   <input type="file" ng-model="data.img" ng-click="upload()"/>

js

   $scope.upload = function() {
                console.log($scope.data.img)

            }
3

4 Answers 4

1

ng-model does not support for file type input. Need to set the value manually to ngModel using a directive like this

.directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
})

call the directive like this

<input type="file" files-input ng-model="data.img" ng-click="upload()"/>

now check the console

Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with a directive. See example here

Comments

1

  • But Instead of directive the easiest is to use HTML5 API, namely FileReader HTML is pretty straightforward:

    Add

In your controller define 'add' method:

$scope.add = function(){
  var f = document.getElementById('file').files[0],
      r = new FileReader();
  r.onloadend = function(e){
    var data = e.target.result;
    //send your binary data via $http or $resource or do anything else with it
  }
  r.readAsBinaryString(f);
}

Reference here

Comments

0

use <input type="file" id="file1" name="file1" multiple onchange="angular.element(this).scope().fileNameChanged('file1')"/> instead of your code,

js

 $scope.fileNameChanged = function(inputField) {


var file = document.getElementById(inputField).files;
console.log(file);

1 Comment

try this one also looks easy .

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.