If you have 4 services that will serve as the data sources for 4 different child views, you can set them up to return references while still allowing access to the promises behind them. The concept is for the views to use the reference during rendering, with the parent using $q.all to wait until all individual promises are resolved before displaying anything.
Service Factories
app.factory('service1', function($http) {
var data1 = [];
return {
promise: $http({...}).success(function(result) {
angular.copy(result, data1);
}),
getData: function() {
return data1;
}
}
});
// Repeat similar factories for service2, service3, and service4
Child Controllers
// Each controller retrieves and assigns data from its respective service
app.controller('ctrl1', function($scope, service1) {
$scope.data1 = service1.getData();
});
// Repeat for ctrl2, ctrl3, and ctrl4
Parent Controller
app.controller('parent', function($scope, $q, service1, service2, service3, service4) {
$q.all(
[service1.promise,
service2.promise,
service3.promise,
service4.promise])
.then(function() {
$scope.done = true;
});
});
Parent View
<div ng-show="done"> All child data loaded </div>
A More Modularized Approach
To avoid the parent controller's dependence on individual data sources and allow flexibility in changing child data sources without impacting the parent, directive-to-directive communication can be utilized. Child directives register their data sources with the parent directive which then utilizes $q.all.
Parent Directive
// Parent directive handling registration of promises from child directives
app.directive('parent', function($q) {
// Implementation code here
});
Child Directive
// Child directives registering with parent directive
app.directive('child', function(service1) {
// Implementation code here
});
HTML
<div parent>
<div child>
<div> {{data1}} </div>
</div>
</div>
Another Efficient Approach
In scenarios where child controllers should not have a dependency on the parent directive, utilizing a parent service can offer a cleaner solution. Child controllers register promises with the parent service, which exposes a method for resolving all child promises collectively.
Parent Service
// Centralized parent service managing promises from child controllers
app.factory('parentService', function($q) {
// Implementation code here
});
Child Controller
// Child controllers registering promises with parent service
app.controller('childCtrl1', function(parentService, service1) {
// Implementation code here
});
// Repeat similar setup for childCtrl2 and other child controllers
Parent Directive
// Parent directive utilizing the parent service for handling child promises
app.directive('parent', function(parentService) {
// Implementation code here
});
HTML
<div parent>
<div ng-show="done">All child data loaded</div>
<div ng-controller="childCtrl1">
{{ data1 }}
</div>
<div ng-controller="childCtrl2">
{{ data2 }}
</div>
</div>