Promise Problem
This fiddle shows (as close as possible) the problem I was having where the promise resolves before the data is loaded.
HTML
<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.min.js"></script>
<div ng-view></div>
<script type=text/ng-template id=a.html>
<p>{{person.name}}</p>
<p>{{person.age}}</p>
</script>
<script type=text/ng-template id=b.html>
<p>{{person.name}}</p>
<p>{{person.age}}</p>
</script>
<a href="#/a">Go to A</a> <a href="#/b">Go to B</a>
JavaScript
var app = angular.module('myApp', []);
app.config(function($routeProvider) {
with($routeProvider) {
when('/a', {controller:'ControllerA', templateUrl: 'a.html', resolve: ControllerA.resolve});
when('/b', {controller:'ControllerB', templateUrl: 'b.html', resolve: ControllerB.resolve});
otherwise({redirectTo: '/a'});
}
});
app.factory('data', function($timeout) {
var person = {};
var dp = {};
dp.setPerson = function(name, age, promise) {
$timeout(function() {
person.name = name;
person.age = age;
promise.resolve();
}, 100)
};
dp.getPerson = function() { return person; }
return dp;
});
function ControllerA($scope, data) {
$scope.person = data.getPerson();
}
ControllerA.resolve = { delay: function(data, $q) {
//Put the promise here and pass it as a parameter to the data retrieval functions.
//Resolve/reject the promise within that function
//This prevents the view from showing up without data to render
var d = $q.defer();
data.setPerson("Kevin", 23, d);
return d.promise;
}
};
function ControllerB($scope, $q, data) {
$scope.person = data.getPerson();
}
ControllerB.resolve = { delay: function(data, $q) {
var d = $q.defer();
data.setPerson("Jordan", 25, d);
return d.promise;
}
};