My challenge lies in using AngularJS to create several global objects accessible by any controller within the application.
One crucial object I require is a user object containing the user's ID and other essential properties retrieved from the database via Ajax. The goal is to establish this user object, then initialize the controllers utilized on the page for an effective initial load of the program.
If the user object remains unset, a redirection becomes necessary.
I am seeking a clean solution for this issue. Despite my attempts with broadcasting, the code is becoming convoluted.
At present, I utilize ui-router and have a hidden view employing a GlobalsCtrl controller. This controller uses a service to fetch the objects and subsequently $broadcasts them for controller initialization. However, this broadcasting solely functions during the initial site load. Events are not broadcasted when changing $location.paths due to the pre-set variables in GlobalsCtrl.
Implementing conditional statements seems like a messy workaround to me.
Your insights would be greatly appreciated. Thank you!
Plunker - http://plnkr.co/edit/TIzdXOXPDV3d7pt5ah8i
var app = angular.module('editor.services', []);
app.factory('AnalysisDataService', ['$http', function($http) {
var self = this;
self.activeAnalysis = {};
self.openAnalysis = function(analysisId) {
return $http.get('api/v1/assignments/analysis/' + analysisId)
.success(function(data, status, headers, config) {
self.activeAnalysis = data;
return self.activeAnalysis;
}).error(function(data, status, headers, config) {
console.log("Error could not load analysis article.");
}).then(function(result) {
return self.activeAnalysis;
});
};
self.getAnalysis = function() {
return self.activeAnalysis;
};
self.navigateToStep = function(step) {
$location.path('/analysis/summary');
};
return {
open: self.openAnalysis,
get: self.getAnalysis,
navigate: self.navigateToStep,
}
}]);
The issue arises as I necessitate setting the self.activeAnalysis variable before certain controllers load. Each page displays differing datasets based on the analysisId.