In AngularJS, when using "controller as" syntax and "this", how to reference "this" inside a promise's callback? In AngularJS, when using "controller as" syntax and "this", how to reference "this" inside a promise's callback? angularjs angularjs

In AngularJS, when using "controller as" syntax and "this", how to reference "this" inside a promise's callback?


You can use angular.bind:

myService.getInventory().then(angular.bind(this, function(data) {  console.log(this.inventory);}));

From angular.bind docs:

Returns a function which calls function fn bound to self (self becomes the this for fn).


You can also save a reference to the context(this) like so:

var self = this;myService.getInventory().then(function(data) {  console.log(self.inventory);});