Reputation: 2184
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?
Upvotes: 5
Views: 62
Reputation: 193261
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.
Upvotes: 9
Reputation: 10132
You can also use angular.bind
for this case
promise.then(angular.bind(this, function (success_data) {
this.php_response = success_data;
}), function (error) {
console.log('there was a problem');
});
Upvotes: 1