上传前的AngularJS图像预览显示所选的上一张图像 [英] AngularJS Image Preview before Upload showing previous image selected
问题描述
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 ',函数(e){
$ scope。$ apply(function(e){
modelSetter($ scope,element [0] .files [0]);
});
$ scope.setimage();
});
}
上面的代码是我的指令。
在函数$ 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;
}
}
每当我选择文件时,
< img width = 250 height = 350 ng-src ={{Imag eSrc}}/>
< input type =`here code`filefile-model =myFile/>
立即预览不显示。当我第二次选择时,先前选择的图像文件的预览正在出现。不知道什么是错的。
而不是 element.bind('change',...
,您可以在myFile上使用 $ scope。$ watch
,如下所示:
modelSetter($ scope ,元素[0] .files [0]);
});
$ scope.setimage();
});
pre>
请注意, $ scope.myFile
需要被定义才会发生,所以如果没有定义您需要将此指令添加到您的控制器中。
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.
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.
这篇关于上传前的AngularJS图像预览显示所选的上一张图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!