debianmaster
debianmaster

Reputation: 503

How to bind image source to file object in angular

I have two elements one file and another image

<input type='file' id='myfile' />
<img id='myImg' >

When i select image using file browse, my image object should be updated with the selected image How can i achieve this using angular?

Upvotes: 2

Views: 4944

Answers (3)

debianmaster
debianmaster

Reputation: 503

Javascript way of doing this is on onchange event is

var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
    $('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(file);

I need it in Angular

Upvotes: 0

Igor Semin
Igor Semin

Reputation: 2496

Use FileReader for this. For example:

html

<div ng-app="app" ng-controller="Controller">
    <img ng-src="{{loadedFile}}" alt="" />
    <input type="file" value="load" onchange="angular.element(this).scope().fileLoaded(this)" />
</div>

code

function Controller($scope) {
    $scope.fileLoaded = function (e) {
        var tgt = e.target || window.event.srcElement,
            files = tgt.files,
            fileReader;

        if (FileReader && files && files.length) {
            var fileReader = new FileReader();
            fileReader.onload = function () {

                $scope.loadedFile = fileReader.result;
                $scope.$apply();
            }
            fileReader.readAsDataURL(files[0]);
        } else {
            // Not supported
        }
    };
});

Look fiddle

Upvotes: 4

Aditya Sethi
Aditya Sethi

Reputation: 10586

You can use ng-flow

Check out Gallery upload from here http://flowjs.github.io/ng-flow/

Hope this helps you!

Upvotes: 0

Related Questions