Om3ga
Om3ga

Reputation: 32823

angular reading a file from file input via readAsDataURL does not work

I have following code.

directive

.directive('area', function () {
    return {
        link: function (scope, el, attrs) {
            var fileReader = new FileReader();

            fileReader.onload = function (e) {
                scope.image = e.target.result;
                scope.$apply();
            }

            el.on('change', function () {
                fileReader.readAsDataURL(el[0].files[0]);
            });
        }
    };
});

controller

.controller('areaController',
    ['$scope', 
        function ($scope) {
            $scope.image = "";
        }
    ]
);

Somehow when I add a image to file input then I get following error

areaDirective.js:19 Uncaught TypeError: Cannot read property '0' of undefined

Upvotes: 1

Views: 1261

Answers (1)

Shivangi
Shivangi

Reputation: 3062

I guess you should modify it to

el.on('change', function (e) {
 var files = (e.srcElement || e.target).files
    fileReader.readAsDataURL(files[0]);
 });

Upvotes: 2

Related Questions