3

There is the following code:

  handleFileSelect = (evt) ->
    console.log(1)
    file = evt.currentTarget.files[0]
    reader = new FileReader()
    reader.onload = (evt) ->
      $scope.$apply ($scope) ->
        $scope.myImage = evt.target.result
      reader.readAsDataURL(file)
  angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect)

And HTML:

<div class="form-group ng-scope">
  <label class="col-sm-2 control-label" for="image">Image:</label>
  <div class="col-sm-10">
    <div class="cropFile">
      <input id="fileInput" type="file">
    </div>
  </div>
</div>

I want to get '1' in console after I change some file in #fileInput. But when I choose file I get nothing. How can I fix it? Thanks!

3
  • <input id="fileInput" type="file" ng-change="handleFileSelect()" /> Commented Jan 6, 2015 at 9:51
  • I add it, add move handleFileSelect to $scope, but it doesn't work.. Commented Jan 6, 2015 at 9:59
  • 1
    any luck with this, having similar problem?? Commented Aug 18, 2015 at 9:08

1 Answer 1

5

Do this by making a directive.

I have created a directive name upload

HTML PART

<div><input style="margin: 0 auto;" type="file" id="fileInput" upload></div>

JS for Directive

myapp.directive('upload', function($rootScope) {
return {
    restrict: 'EA',
    link: function(scope, elem, attrs) {
        elem.on("change" ,function(evt) {
            var file = evt.currentTarget.files[0];
            var reader = new FileReader();
            reader.onload = function(evt) {
                scope.$apply(function($scope) {
                    $rootScope.myImage = evt.target.result;
                    console.log($rootScope.myImage);
                });
            };
            reader.readAsDataURL(file);
        });
    }
  };
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.