I came across this question and made some modifications. It works well when used outside of the ng-repeat
.
However, I'm facing issues when trying to use it within my repeat loop; the image.src
does not update. I believe this is more related to the scope rather than the preview function itself. The console log on line 13 in the Plunker shows a string image
, which should actually be the object from the loop.
So, how can I achieve the preview image after selecting a file?
HTML:
<div ng-repeat="image in data.CmsPageImages">
<a href="" ng-click="removeImage($index)" class="pull-right">
<i class="fa fa-times"></i>
</a>
<input
image-callback="test1"
type="file"
wa-file-select
ng-model="image.file">
<input
type="text"
required
placeholder="Caption and copyright"
ng-model="image.caption">
<img ng-if="image.src" ng-src="image.src" style="width: 120px; height: auto;" />
</div>
JS code:
angular.module('waFrontend', []);
angular.module('waFrontend').directive('waFileSelect', ['fileReader', function (fileReader) {
return {
require: '^ngModel',
scope: {
imageData: '='
},
link: function ($scope, el, attr) {
el.bind('change', function(e) {
var file = ((e.srcElement || e.target).files[0]);
fileReader.readAsDataUrl(file, $scope).then(function (result) {
attr.imageData.src = result;
});
})
}
}
}]);
angular.module('waFrontend').controller('SubmitNewsController', [
'$scope', 'fileReader',
function ($scope, fileReader) {
$scope.data = {
CmsPage: {
title: ''
},
CmsPageImages: [
{
caption: '',
file: null
}
]
};
$scope.addImage = function() {
$scope.data.CmsPageImages.push({
caption: null,
file: null
});
};
$scope.removeImage = function(index) {
$scope.data.CmsPageImages.splice(index, 1);
};
$scope.getFile = function(file, test) {
$scope.progress = 0;
$scope.file = file;
fileReader.readAsDataUrl($scope.file, $scope).then(function (result) {
$scope.imageSrc = result;
});
};
}]);
(function (module) {
var fileReader = function ($q, $log) {
var onLoad = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.resolve(reader.result);
});
};
};
var onError = function (reader, deferred, scope) {
return function () {
scope.$apply(function () {
deferred.reject(reader.result);
});
};
};
var onProgress = function (reader, scope) {
return function (event) {
scope.$broadcast("fileProgress",
{
total: event.total,
loaded: event.loaded
});
};
};
var getReader = function (deferred, scope) {
var reader = new FileReader();
reader.onload = onLoad(reader, deferred, scope);
reader.onerror = onError(reader, deferred, scope);
reader.onprogress = onProgress(reader, scope);
return reader;
};
var readAsDataURL = function (file, scope) {
console.log(file);
var deferred = $q.defer();
var reader = getReader(deferred, scope);
console.log(file);
reader.readAsDataURL(file);
return deferred.promise;
};
return {
readAsDataUrl: readAsDataURL
};
};
module.factory("fileReader", ["$q", "$log", fileReader]);
}(angular.module("waFrontend")));