how to set angular controller element using http get return values

48 views Asked by At

I am using http get function to get json array from service. How can I set response to controller locations element.

function MainCtrl($http,myService) {
    this.locations = null;
    myService.async().then(function(d) {
        ? = d;
    });
}

Response d is well-formed (JSON)

2

There are 2 answers

1
Callum Linington On BEST ANSWER

You just take a reference to the current context and then use that variable reference in the callback

function MainCtrl($http,myService) {
    var vm = this;

    vm.locations = []; // initialise properly
    myService.async().then(function(d) {
        vm.locations = d;
    });
}
0
skubski On

There is a different approach to this problem too. I added my 'answer' for the sake of completeness. It is also possible to bind the this reference to your function. This can be achieved in two ways, by either using the angular.bind() or the native javascript bind to pass this reference.

e.g.:

function MainCtrl($http,myService) {
    this.locations = []; // initialise properly

    myService.async().then(function(d) {
        this.locations = d;
    }.bind(this));
}

P.S.: I tried to edited your answer and add this solutions to this problem of different scopes but it got rejected. For the following reason:

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer

Not to take aim at the reviewers but they sure don't realize I can't post any comment with the current rep I have nor does it make sense to answer an answered question.