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.

user1062383
  • 39
  • 1
  • 6
  • you need to $apply() your change. Can probably find some use in these methods: http://www.jeffryhouser.com/index.cfm/2014/6/2/How-do-I-run-code-when-a-variable-changes-with-AngularJS – rg88 Dec 07 '15 at 23:14

2 Answers2

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.

jperezov
  • 3,041
  • 1
  • 20
  • 36
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;
    });  }
   }
user1062383
  • 39
  • 1
  • 6