-1

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'

UrhoKarila
  • 354
  • 5
  • 25
  • @trincot Although the question you linked gives me a good idea of *what's* going wrong, it doesn't give a particularly concise idea of *how to fix it*. I'm not sure that closing this as duplicate is the correct course at this time -- leaving it open for an answer will, I think, help others down the road who experience the same issue. – UrhoKarila Nov 18 '16 at 19:57
  • There are many ways out. Here is one: `xhr.onload = function () { ... }.bind(this);`. – trincot Nov 18 '16 at 20:02
  • Thanks, that did the trick! I do still stand by my earlier assertion, though -- this question should not be marked as duplicate, and your comment really [should have been made an answer](http://meta.stackoverflow.com/a/297069/1673882). – UrhoKarila Nov 18 '16 at 20:17
  • The thing is that this question has been asked hundreds of times in many flavours. Here is [another that explains it well](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback), and has the bind solution explained under the heading "Explicitly set this". – trincot Nov 18 '16 at 20:25
  • Then can we change the duplicate flag to point at that question instead? The discussion on the 'this' keyword is illuminating, but is less useful as a linked question/answer than [this](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback). – UrhoKarila Nov 18 '16 at 20:28

1 Answers1

0

There are many ways out. Here is one:

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

You can find more info in this question & answer

Community
  • 1
  • 1
trincot
  • 211,288
  • 25
  • 175
  • 211