admin管理员组

文章数量:1405380

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!

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!

Share Improve this question asked Jan 6, 2015 at 9:49 malcoaurimalcoauri 12.2k28 gold badges88 silver badges141 bronze badges 3
  • <input id="fileInput" type="file" ng-change="handleFileSelect()" /> – devqon Commented Jan 6, 2015 at 9:51
  • I add it, add move handleFileSelect to $scope, but it doesn't work.. – malcoauri Commented Jan 6, 2015 at 9:59
  • 1 any luck with this, having similar problem?? – Andrei Maieras Commented Aug 18, 2015 at 9:08
Add a ment  | 

1 Answer 1

Reset to default 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);
        });
    }
  };
});

本文标签: javascriptAngularJs element on change eventStack Overflow