I'm having a problem understanding promises in AngularJS.
I have something like the following:
var loader = angular.module('loadIt', []);
loader.factory('loadService', function($http, $q) {
return {
getJs: function(path) {
var deferred = $q.defer();
$http.get(path).then(function(response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
}
});
var myMod = angular.module('myMod', ['loadIt']);
myMod.service('mymodService', function(loadService) {
this.vals = {};
this.readIt = function (pos) {
this.vals[pos] = loadService.getJs('aaa.js');
}
});
In the debugger, I see the line:
this.vals[pos] = loadService.getJs('aaa.js');
The correct value is being returned by the getJs() call. But the scope is wrong. this.vals isn't defined inside the readIt function. How can I fix that?
Edit
I also tried the following:
this.readIt = function (pos) {
loadService.getJs('aaa.js').then(function(data) {
this.vals[pos] = data;
});
}
Here I see that data contains the JSON object read from a file.
this refers to object Window and this.vals does not exist in the scope.