Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the "this" of an angular js controller, from inside a promise method?

I have simple angular js controller making a XHR request as below

app.controller('MainController', ['$http', function($http) {

    this.php_response = {};

    var promise = $http.get('process.php');

    promise.then(
        function(success_data) {

            // I dont think "this" is talking to the controller this anymore?    
            this.php_response = success_data;

        }, function(error) {
            console.log('there was a problem');
        }
    );

}]);

When I wrote this controller using $scope instead of this the code worked, now the this.php_response property is not containing the data retrieved from the XHR request.
I suspect the promise.then#success callback is no longer referencing the controller this.
How can I get access the this, inside the promise method?

like image 810
the_velour_fog Avatar asked May 16 '15 11:05

the_velour_fog


1 Answers

Use arrow function that preserves lexical context:

promise.then(success_data => {  
    this.php_response = success_data;
}, error => {
    console.log('there was a problem');
});

Another simple way is to bind context with Function.prototype.bind method:

promise.then(function(success_data) {  
    this.php_response = success_data;
}.bind(this), function(error) {
    console.log('there was a problem');
});

And finally, old-school way: define reference variable pointing to outer this and use it inside callback:

var self = this;

promise.then(function(success_data) {  
    self.php_response = success_data;
}, function (error) {
    console.log('there was a problem');
});

Whatever you prefer more.

like image 85
dfsq Avatar answered Nov 14 '22 23:11

dfsq