My goal is to efficiently pass data between controllers after each successful HTTP request. This is the current hierarchy:
<div ng-controller="ParentCtrl as parent">
<div ng-controller="ChildOneCtrl as chi1"></div>
<div ng-controller="ChildTwoCtrl as chi2"></div>
<div ng-controller="ChildThreeCtrl as chi3"></div>
</div>
The loading of data in each subsequent controller depends on the success of the previous one.
ChildOneCtrl:
function ChildOneCtrl ($scope, sharedService) {
var chi1 = this;
sharedService.getChildOneData()
.then(function (res) {
$rootScope.$emit('childOneDataEmited', res.data);
}).catch(function (err) {
console.log(err);
});
}
ChildTwoCtrl:
function ChildTwoCtrl ($scope, $rootScope, sharedService) {
var chi2 = this;
var onEmitChildOne = $rootScope.$on('childOneDataEmited', function (event, data) {
getData(data);
});
$scope.$on('$destroy', onEmitChildOne);
function getData(data){
var chi1Data = data;
if(chi1Data.uEnabled){
sharedService.getChildTwoData()
.then(function (res) {
$rootScope.$emit('childTwoDataEmited', res.data);
}).catch(function (err) {
console.log(err);
});
}
}
}
ChildThreeCtrl:
function ChildThreeCtrl ($scope, $rootScope, sharedService) {
var chi3 = this;
var onEmitChildThree = $rootScope.$on('childTwoDataEmited', function (event, data) {
getData(data);
});
$scope.$on('$destroy', onEmitChildThree);
function getData(data){
var chi2Data = data;
sharedService.getChildThreeData()
.then(function (res) {
//to do some data manipulation
console.log(res)
console.log(chi2Data)
}).catch(function (err) {
console.log(err);
});
}
}
Although this solution works, I anticipate changes in the hierarchy that may make it more complex. I am looking for a more efficient way to handle data passing without relying too heavily on events.