mcbjam mcbjam - 6 months ago 44
AngularJS Question

How to refresh an image after src change in Angular JS

I would like to selecta file and load it in angular js.

Everything work fine, the only problem the image don't refrech. I can see that everything work because when i toggle the on menu on my page with angular.js the image is been refreshing.

Here is my code :

<div ng-controller="TopMenuCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<input ng-model="photo"
onchange="angular.element(this).scope().file_changed(this)"
type="file" accept="image/*" multiple />
<output id="list"></output>
<img ng-src="{{imageSource}}">
</div>


And the Angular js script :

$scope.file_changed = function(element) {
var files = element.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, photofile; photofile = files[i]; i++) {

// var photofile = element.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {

$scope.imageSource= e.target.result;

};
})(photofile);

reader.readAsDataURL(photofile);
};

}

Answer

You must call Scope.$apply when you manually update $scope.imageSource in the onLoad function, because Angular can't guess when you make this change.