1
    myApp.directive('fileModel', ['$parse', function($parse) {
    return {
      restrict: 'A',
      link: function($scope, element, attrs) {
    var model = $parse(attrs.fileModel);
    var modelSetter = model.assign;
    element.bind('change', function(e) {
      $scope.$apply(function(e) {
        modelSetter($scope, element[0].files[0]);
      });
      $scope.setimage();
    });
  }

The above code is my directive.

In the function $scope.setimage()

     $scope.setimage = function() {
  var file = $scope.myFile;
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function(e) {
    $scope.ImageSrc = e.target.result;
  }
}

Whenever i choose the file,

  <img width= 250 height=350 ng-src="{{ImageSrc}}"/>
  <input type=`enter code here`"file" file-model="myFile"/>

Immediately the preview is not appearing. When i choose the second time, the preview for the previously selected image file is appearing. Not sure what is wrong.

1

2 Answers 2

0

Instead of element.bind('change', ..., you can use $scope.$watch on myFile, like so:

$scope.$watch('$scope.myFile', function(e) {
  $scope.$apply(function(e) {
    modelSetter($scope, element[0].files[0]);
  });
  $scope.setimage();
});

Note that $scope.myFile needs to be defined for this to occur, so if it's not defined in your directive you'll need to add this to your controller instead.

Sign up to request clarification or add additional context in comments.

Comments

0

I added $scope.$apply for the imagesrc assignment and the image updated immediately.

   $scope.setimage = function() {
   var file = $scope.myFile;
   var reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function(e) {
     $scope.$apply(function(){
      $scope.ImageSrc = e.target.result;
    });  }
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.