UrhoKarila UrhoKarila - 21 days ago 5
AngularJS Question

Attempting to call a method from an onload(), am told method is not supported

I'm attempting to make a simple Angular form for uploading user input. One of the steps involves selecting an image. I'm trying to fetch an image from a remote source, before uploading it to a server.

app.controller('submissionFormController', function ($http) {
this.formIsVisible = false;
...
this.sub = { //this Object contains the data entered into the form
};

this.uploadImage = function(img){
this.sub.imgfile = img;
};

this.downloadImage = function () {
url = this.sub.imgurl;
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';

xhr.onload = function () {
this.uploadImage(xhr.response);
console.log("Image fetched!");
};

xhr.open('GET', url);
xhr.send();
};
});


When executing the code, I get the following error:

Object doesn't support property or method 'uploadImage'

Answer

There are many ways out. Here is one:

xhr.onload = function () { ... }.bind(this);

You can find more info in this question & answer