$q.all() play-date with ang_resource.query().$promise
http://angularjs.org/
HTML
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.0.4/css/bootstrap.min.css">
<script src="http://code.angularjs.org/1.0.1/angular-mocks-1.0.1.js"></script>
<script src="http://code.angularjs.org/1.0.1/angular-resource-1.0.1.min.js"></script>
<div ng-app="q_all_test">
<div ng-controller="MainCtrl">
<p>{{msg}}</p>
(console for more info)
</div>
</div>
JavaScript
var q_all_test = angular.module('q_all_test', ['ngMockE2E', 'ngResource']);
q_all_test.run(function($httpBackend) {
var foos_list = [
{ _id: 123213, name: 'yadda A'},
{ _id: 234234, name: 'yadda B'},
{ _id: 322223, name: 'yadda C'}];
var bars_list = [
{ _id: 123213, name: 'yadda A'},
{ _id: 234234, name: 'yadda B'},
{ _id: 322223, name: 'yadda C'}];
$httpBackend.whenGET(/\/api\/foos/).respond(function(method, url, data, headers) {
return [200, foos_list];
});
$httpBackend.whenGET(/\/api\/bars/).respond(function(method, url, data, headers) {
return [200, foos_list];
});
});
q_all_test.controller( 'MainCtrl', ['$scope', '$rootScope', '$resource', '$q', '$timeout', function($scope, $rootScope, $resource, $q){
var Res1 = $resource('/api/foos');
var Res2 = $resource('/api/bars');
$scope.msg = '';
$rootScope.foos = Res1.query(function(){console.log('$rootScope.foos is ', $rootScope.foos);});
$rootScope.bars = Res2.query(function(){console.log('$rootScope.foos is ', $rootScope.bars);});
$q.all([$rootScope.foos.$promise, $rootScope.bars.$promise])
.then(function(){
console.log('$rootScope.foos inside $q.all() is ',$rootScope.foos);
console.log('$rootScope.bars inside $q.all() is ',$rootScope.bars);
if ($rootScope.foos.length > 0 && $rootScope.bars.length > 0){
$rootScope.$broadcast('foos_and_bars!');
} else {
$scope.msg = 'Not expected; The promoises inside $q.all([p1,p2]).then() do not appear to be resolved.';
}
});
$rootScope.$on('foos_and_bars!', function(){
// (My intent with doing this is to broadcast an event which is sure to be after n resources are loaded)
$scope.msg = 'Expected; $rootScope.foos and $rootScope.bars have values inside of $q.all().then()';
});
}
]);