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();
});
}上面的代码是我的指令。
在函数$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="{{ImageSrc}}"/>
<input type=`enter code here`"file" file-model="myFile"/>预览立即不出现。当我选择第二次时,会出现先前选择的图像文件的预览。不知道是怎么回事。
发布于 2015-12-07 23:22:51
与element.bind('change', ...不同,您可以在myFile上使用$scope.$watch,如下所示:
$scope.$watch('$scope.myFile', function(e) {
$scope.$apply(function(e) {
modelSetter($scope, element[0].files[0]);
});
$scope.setimage();
});请注意,需要定义$scope.myFile才能实现这一点,因此如果指令中没有定义它,则需要将其添加到控制器中。
发布于 2015-12-09 05:03:04
我为imagesrc分配添加了$scope.$apply,并立即更新了图像。
$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;
}); }
}https://stackoverflow.com/questions/34145096
复制相似问题