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

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to