the_velour_fog the_velour_fog - 3 months ago 6
AngularJS Question

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?

Answer

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.