I am having an issue with my upload component where the view is not updating when the onchange event fires. Even though I can see the file names being logged, nothing is happening on the screen.
My approach involves using a directive so that I can easily integrate the file uploader into any project by simply adding
<upload url='/fileserver'></upload>
.
Controllers:
var controllers = {
UploadCtrl: function ($scope) {
$scope.images = [];
$scope.files = [];
$scope.upload = function (element) {
$scope.$apply(function ($scope) {
$scope.files = element.files;
});
};
$scope.$watch('files', function () {
for (var i = 0; i < $scope.files.length; i += 1) {
var current = $scope.files[i];
var reader = new FileReader();
reader.onload = (function (file) {
return function (env) {
console.log(file.name);
$scope.images.push({ name: file.name, src: env.target.result });
}
}(current));
reader.readAsDataURL(current);
}
}, true);
}
};
Directives:
var directives = {
upload: function ($compile) {
return {
restrict: 'E',
link: function (scope, element, attr) {
scope.url = element.attr('url');
element.html($compile(template)(scope));
}
};
}
};
Template var (contains multi-line strings stored in a cs file)
template = """
<div ng-controller='UploadCtrl'>
<input type='file' multiple onchange='angular.element(this).scope().upload(this)' />
<div ng-repeat='image in images'>
{{image.name}}: <img ng-src='{{image.src}}' width='80' height='80' />
</div>
</div>
"""