Resolving Promise in a WebSQL Callback
HTML
<div ng-view></div>
<script type=text/ng-template id=a.html>
<div ng-controller="AppCtrl">
<p>{{person.name}}</p>
</div>
</script>
JavaScript
var app = angular.module("myApp", []);
app.config(function($routeProvider) {
with($routeProvider) {
when("/", {templateUrl:"a.html", controller:'AppCtrl', resolve:AppCtrl.resolve});
otherwise({redirectTo:'/'});
}
});
app.service('data', function($q) {
var person = {};
return {
fetchPerson: function(d) {
setTimeout(function() {
person.id = 1;
person.name= "Kevin";
d.resolve();
/*
So here's the problem - the deferred object won't resolve, or at least
it will resolve, but Angular doesn't pick it up. Now from the documentation
it says that I should wrap the line in a $scope.$apply block, but which $scope
should I use? $rootScope? I hear it's bad practice and "messy" to inject
$rootScope into Services.
I used a simple timeOut function in this instance but my actual use case is
the success callback function of a db.transaction() execution.
*/
}, 2000)
},
getPerson: function() { return person; }
}
});
function AppCtrl($scope, data) {
$scope.person = data.getPerson();
}
AppCtrl.resolve = {
delay: function($q, data) {
var d = $q.defer();
data.fetchPerson(d);
return d.promise;
}
/* I realized that the reason it was resolving was because of the $timeout function
you called in the following function. Note how now that it's commented out, the view
doesn't load, but remove the comment and see that the view loads.
What's causing this and how do I fix it?
*/
person: function($q, $timeout) {
var d = $q.defer();
$timeout(function() {
d.resolve({name:"John"});
}, 2000);
return d.promise;
}
}