简体   繁体   中英

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?

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.

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM