I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this:
this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) =>
{
this.StockItems = StockItems;
this.CreditNoteStockItems = new Array<ViewModels.CreditNoteStockItemViewModel>();
}
Despite having all members defined in the controller before calling this service method, once the promise is resolved, both this.StockItems and this.CreditNoteStockItems become undefined. Additionally, the assignment of StockItems doesn't seem to reflect in the view. I suspect this might be due to a scope issue where the promise is returning into a new scope. This strange behavior has occurred with other methods as well, seemingly at random.
Could someone shed some light on why this is happening and, more importantly, suggest ways to prevent it from happening again?
Note: The provided code snippet is a simplified version of my controller (excluding additional members and methods).
Additional information about the method in the controller:
export class CreditNoteController
{
static $inject = ['$scope', '$modalInstance', 'StockService'];
StockService: Services.StockService;
ModalInstance: ng.ui.bootstrap.IModalServiceInstance;
constructor($scope, $modalInstance, StockService: Services.StockService)
{
$scope.vm = this;
this.ModalInstance = $modalInstance;
this.StockService = StockService;
}
InvoicesSelectionChanged()
{
this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) =>
{
this.StockItems = StockItems;
this.CreditNoteStockItems = new Array<ViewModels.CreditNoteStockItemViewModel>();
});
}
}
The controller is injected through the angular UI modal service open method located in another controller:
this.ModalService.open(
{
templateUrl: URL,
controller: Controllers.CreditNoteController,
});
Some additional insight on the generated JavaScript:
CreditNoteModalController.prototype.InvoicesSelectionChanged = function () {
var _this = this;
this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success(function (StockItems) {
_this.StockItems = StockItems;
_this.CreditNoteStockItems = new Array();
});
};
Any help or guidance would be greatly appreciated. Thank you!