I am happily using the file selector from solution @Snowman's answer to this question
Now, however, I want to use it in an ng-repeat
loop, and am stuck.
I take the liberty of copying the solution from that question:
angular
.module('app.services')
.directive('fileChange', function() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function (scope, element) {
element.on('change', function (event) {
scope.$apply(function(){
scope.handler({files: event.target.files});
});
});
}
};
});
<input type="file" file-change handler="fileSelect(files)">
$scope.fileSelect = function(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
console.log("on load", e.target.result);
}
reader.readAsText(file);
}
How do I indicate to the $scope.fileSelect()
function which photo has just had its file selected?
[Update] Aargh! I just realized that I did not make the question clear enough. I need the file name, and some other data from the repeat. Let's say that I want a file name and a description of the image, entered by the user.
So, I have declared
$scope.image = {'fileName' : '',
'description' : ''};
$scope.images = []; // array of $scope.image
And, in the HTML, in the ng-repeat
, I will have (pseudo code only)
<ng-repeat image in images>
<input type="text" ng-model="image.description"/>
<input type="file" file-change handler="fileSelect(files)">
It's the last <input>
that I don't know how to code. Ideally, I want to pass the image
object to the file-change handler
function.
How can I do that?
[Final update] just in case anyone every reads this & finds it interesting.
<ng-repeat image in images>
<input type="text" ng-model="image.description"/>
<input type="file" file-change handler="fileSelect(image , files)">
added a image
parameter, and also to $scope.fileSelect(image , files)
in the controller. Note that no change was required on the directive.
Works like a charm