Image upload + FileReader preview. Trouble with binding between controller and directive and scope

145 views
Skip to first unread message

Emil

unread,
Mar 21, 2016, 5:10:04 AM3/21/16
to AngularJS
Hi,

I'm relatively new to Angular and are stilling trying to wrap my head around all it's magic and scoping.

I'm trying to do a simple image upload with preview script and I'm missing the final piece.

I have managed to do each task (the upload and the preview) separately but I'm stuck with piecing it together.

This is my code so far:

JS
angular.module('fileUpload', [])

 
.controller("upload", ['$scope', '$http', function($scope, $http){
    $scope
.$watch('file', function(file){
      console
.log("arguments", file);
     
// Upload file via $http, formdata & transformRequest
   
});
   
 
}])

 
.directive("fileinput", [function() {
   
return {
      scope
: {
        fileinput
: "="
     
},
      link
: function(scope, element, attributes) {
        element
.bind("change", function(changeEvent) {
          scope
.fileinput = changeEvent.target.files[0]; // Trigger $watch in controller
         
         
var reader = new FileReader();
          reader
.onload = function(loadEvent) {
            scope
.$apply(function() {  
             
// Should add the base64 for my filepreview variable
              scope
.filepreview = loadEvent.target.result;
           
});
         
}
          reader
.readAsDataURL(scope.fileinput);
       
});
     
}
   
}
 
}]);


HTML
<input type="file" fileinput="file" />

<img ng-src="{{filepreview}}" class="image"/>

So, as you might see, I'm binding the fileinput in the directive to the $scope.file in the controller. It works. When a change in the file input is triggered, the file variable in the controller is obtaining the correct data for me to send it and upload it.
My problem right now is, that I'm using the fileinput in the directive to call the FileReader,  run the readAsDataURL and then listen to when that's done, apply it to the scope and here I stop. I want to update the variable filepreview so it will be updated in the template (see HTML and IMG) but I simply cannot figure out how to connect the two.
The filepreview should not be saved and is only to show to the user what image they just selected.

So, essentially, I want to bind the scope.filepreview with the filepreview from e.g. the controller.

How would I go about doing that?

Thanks,
- Emil

Sander Elias

unread,
Mar 21, 2016, 11:26:02 PM3/21/16
to AngularJS
Hi Emil,

The problem is that you created a directive with an isolate scope. That scope is not available outside the directive. The smart thing to do now, is to move the whole thing into a component. That way you are 'bundling' the html and the logic and your problem goes away.
Have a go at this. If  you have questions, don't hesitate to ask ;)

Regards
Sander
Reply all
Reply to author
Forward
0 new messages