AngularJS - self referencing services?
angularjs, angularjs-service
Solution
How about something like this:
globalModule.factory('global', function($http) {
var glob = {
squareMgr: {
// ...
},
missionMgr: {
foo: function() {
glob.squareMgr.xyz();
}
}
};
return glob;
});
Problem
I'm building an Angular app that will have a top-level Controller and a second-level controller. There will be n number of second-level controllers, but I want to put global-level functions someplace. I'm doing this in a service. I'm starting down the path of creating a single service that return an api, really, containing lots of functions (below). The service is returning an object with two property branches that each contain a set of functions. How can I call one of these from the other? ``` globalModule.factory('global', function($http) { var squares = MyApp.squares; // this is the *only* link from Global namespace to this app return { squareMgr: { getSquaresEarned: function() { return squares.earned; }, getSquaresPlaced: function() { return squares.placed; }, setThisSquareEarned: function(value) { squares.earned.push(value); }, setThisSquarePlaced: function(value) { squares.placed.push(value); } }, missionMgr: { missionInfo: {}, setMissionInfo: function(missionInfo) { this.missionInfo = missionInfo }, complete: function(missionData) { log('complete called on video at ' + new Date()); missionData.complete = true; log(angular.toJson(missionData)); $http({ url: '/show/completeMission', method: "POST", data: missionData }) .then(function(response) { if (response.data.success === true) { log('completeMission success'); // increment squares earned counter this.squareMgr.setThisSquareEarned(missionData.id); // above is an attempt to run a function contained in this // same service in a different parent property branch. // how *should* I do this? } }); } } } }); ```