File pick with Angular JS

后端 未结 8 763
时光取名叫无心
时光取名叫无心 2020-12-08 07:50

I would like to pick up a file with AngularJS:

HTML:

8条回答
  •  遥遥无期
    2020-12-08 08:08

    I used above method trying to load a preview image when new file is selected, however it didnt work when I tried it like that:

    $scope.file_changed = function(element, $scope) {
    
         $scope.$apply(function(scope) {
             var photofile = element.files[0];
             var reader = new FileReader();
             reader.onload = function(e) {
                $scope.prev_img = e.target.result;
             };
             reader.readAsDataURL(photofile);
         });
    });
    

    I digged more into it and found that the $scope.$apply should be inside the reader.onLoad otherwise changing a $scope variables wont work, so I did the following and it worked:

    $scope.file_changed = function(element) {
    
            var photofile = element.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                $scope.$apply(function() {
                    $scope.prev_img = e.target.result;
                });
            };
            reader.readAsDataURL(photofile);
     };
    

提交回复
热议问题