2015-11-27 164 views
1

當我選擇一個圖像時,有時它不會顯示,但是當我再次單擊時,圖像顯示。使用jQuery顯示圖像

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/*" > 

如何解決這個問題呢?當用戶選擇一個圖像時,我需要顯示圖像。提前致謝。

+0

我認爲這會幫助你更多http://stackoverflow.com/questions/28235246/angularjs-display-base64-image –

+0

你在哪裏點擊來顯示圖像? – sideroxylon

+0

感謝重播@Prajwal KM,但我不用於存儲圖像在遠程服務器我只用於顯示圖像 –

回答

1

好。我給你..加入這一行:

$scope.$apply(); 

爲下面的代碼:

$('#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); 
       } 
      }); 

我也遇到了這個問題。但是這樣解決了。我不知道爲什麼我需要做$scope.$apply();。我沒有足夠的時間來挖掘這些東西。如果有人知道它的原因,歡迎您對我的回答發表評論。

+0

這對我的工作感謝@Chintan Soni –

0

試試這個:

$(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>

+0

但我想顯示多個圖像@sideroxylon –

+0

已更新,以接受多個輸入 – sideroxylon