I'm attempting to create a factory that stores the result of an AJAX call in a variable. So far, I have something along these lines:
angular.module('frontApp')
.factory('myFactory', function(Restangular) {
var myFactory = function() {
this.loadedData = [];
loadData()
}
var loadData = function() {
Restangular.all('endPoint').customGET('path/run').then(
function(success) {
this.loadedData = success.results;
}
);
}
return stoppingPatternFactory;
});
But I get an error: cannot set property 'loadedData' of undefined
.
I understand that the this
keyword in this context refers to the function context which is why I'm getting the error. The issue is that I cant wrap my head around how to set this.loadedData
in the first function when the Restangular call is asynchronous. I've tried just making the request in the first function and trying to set the variable in the callback, but I get the same error.
EDIT: I should probably add that I'm trying to create multiple instances of this factory, e.g. var f = new myFactory()
so that each instance of a directive has its own factory associated with it.