I'm trying to move all my AJAX from an Angular controller into a service. My code worked fine in the controller, but I can't get the same $http requests to run in the service. When I run the following code, Data.tracker is set to "function started" and then never changes.
app.service("Data", function($http) {
this.tracker = "not started";
this.loadHumanReadableNames = function() {
this.tracker = "function started";
$http.get('http://proteomics.ysu.edu/secretomes/animal/index.php/api/get_human_readable_names/').
success(function(data, status, headers, config) {
this.tracker = "ajax successful";
}).
error(function(data, status, headers, config) {
this.tracker = "ajax failed";
});
};
});
app.controller('GlobalController', function($scope, Data) {
$scope.Data = Data;
$scope.initializeData = function () {
//load human readable names
Data.loadHumanReadableNames();
}
});
Any ideas?
UPDATE
MajoB's answer works great. However, for modularity I generally prefer to handle data processing in my model (service) instead of in my controller. The problem with the above code is that this is not available in the success and error functions. The following will print "ajax successful":
in the service:
app.service("Data", function($http) {
this.tracker = "not started";
var self = this;
this.loadHumanReadableNames = function() {
this.tracker = "function started";
$http.get('http://proteomics.ysu.edu/secretomes/animal/index.php/api/get_human_readable_names/').
success(function(data, status, headers, config) {
self.tracker = "ajax successful";
}).
error(function(data, status, headers, config) {
self.tracker = "ajax failed";
});
};
});