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
});
}));
}]);
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With