Reputation: 34632
I am trying to create a upload component but my view isn't updating when onchange event fires. I see the file.names being logged but nothing is happening.
I am using a directive because I would like to be able to just drop my package into a project and then enable the file uploader with <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 (it's a cs file cause of multi line strings)
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>
"""
Upvotes: 0
Views: 1810
Reputation: 412
You may need to use $apply to update the images:
$scope.$apply(function () {
$scope.images.push({ name: file.name, src: env.target.result });
}
Upvotes: 5