1

When I pick an image, at times it does not display, but when I click a second time, the image is displayed.

jQuery

$('#morefiles').change(function (event) {
  if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) {
    $ionicPopup.alert({
      title: 'Message',
      template: 'You must select an image file only !'
    });
    $('#morefiles').val('');
  } else {
    var obj = {};
    obj.key = event.target.files[0];
    obj.value = URL.createObjectURL(event.target.files[0]);
    $scope.items.push(obj);
    console.log(JSON.stringify(obj));
    $('#morefiles').val(obj);
  }
});

HTML

<input type="file" multiple="" id="morefiles" accept="image/*" >

How to solve this problem? When the user selects an image I need to display the image at that time. Thanks in advance.

dda
  • 6,030
  • 2
  • 25
  • 34
Jatin Devani
  • 190
  • 3
  • 15

2 Answers2

1

Okay. I got you.. Add this line:

$scope.$apply();

to your code as below:

$('#morefiles').change(function (event) {
                if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) {
                    $ionicPopup.alert({
                        title: 'Message',
                        template: 'You must select an image file only !'
                    });
                    $('#morefiles').val('');
                } else {
                    var obj = {};
                    obj.key = event.target.files[0];
                    obj.value = URL.createObjectURL(event.target.files[0]);
                    $scope.items.push(obj);
                    $scope.$apply()
                    console.log(JSON.stringify(obj));

                    $('#morefiles').val(obj);
                }
            });

I too faced this problem. But solved this way. I dont know why I need to do $scope.$apply();. I dont have enough time to dig the stuff. If anyone knows the reason for it, you are most welcome to comment my answer.

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
0

Try this:

$(function() {
  $('#morefiles').on('change', gotPic);
});

function gotPic(event) {
  if (event.target.files.length) {
    for (var i = 0; i < event.target.files.length; i++) {
      if (event.target.files[i].type.indexOf('image/') == 0) {
        var src = URL.createObjectURL(event.target.files[i])
        $('#preview').append('<img src = ' + src + '><br>');
      }
    }
  }
}
img {
  width: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple="" accept="image/*;capture=camera" id="morefiles">
<br>
<div id="preview"></div>
sideroxylon
  • 4,338
  • 1
  • 22
  • 40