Among the multitude of discussions on sharing data between controllers, I have yet to come across a satisfactory solution for my particular scenario.
In my setup, one controller fetches data asynchronously using promises. This controller then creates a copy of the data within its scope. I also have a second controller that needs to work with the same copied data as the first controller so that they both share it.
Here is a simplified example of the code:
.controller('firstController', function ($scope, someService){
var vm = this;
someService.getData().then(function(data) {
angular.copy(data, vm.data); //creates a copy and places it on scope
someService.setCurrentData(vm.data)
}
});
.controller('secondController', function ($scope, someService){
var vm = this;
vm.data = someService.getCurrentData(); //Triggers before the setter in firstController
});
.factory('someService', function(fetchService){
var _currentData = {};
var getData = function(){
return fetchService.fetchData().then(function(data) { return data; });
};
var getCurrentData = function(){
return _currentData;
}
var setCurrentData = function(data){
_currentData = data;
}
});
Due to the asynchronous nature of getData, the setCurrentData function may be triggered after getCurrentData, resulting in different objects being returned instead of the correct one. While solutions like broadcast and watch exist, I'm looking for an alternative method to avoid using them if possible.