Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have some data being returned inside a then(), which I need to get stored inside the "this" variable. Since it's not being stored inside the scope, and since it's wrapped inside a callback, my controller's "this" is not valid. How can I bubble the data back up so it can be stored inside "this"? See below:

angular.module('logisticsApp.controllers').
controller('InventoryCtrl', ['$scope', '$http', '$window', 'DataService', 
    function ($scope, $http, $window, DataService) {

    this.inventory = ''; // need to have data stored here

    $scope.$on('$viewContentLoaded', angular.bind(this, function() {
      // "this" is still valid here
      myService.getInventory().then(function(data) {
        // "this" is no longer valid!
        $scope.inventory = data; // so this fails
      });
    }));
}]);
like image 403
rakelblujeans Avatar asked Jan 10 '23 11:01

rakelblujeans


1 Answers

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);
});
like image 139
Ilan Frumer Avatar answered Jan 29 '23 11:01

Ilan Frumer