Possible Duplicate:
angularjs - promise never resolved in controller
I'm wrapping a slow WebSockets server in a AngularJS service, and then calling into that service from my controllers. If I chain callbacks onto callbacks onto callbacks, everything works just fine, any the UI updates asynchronously.
When I try to use $q.defer()
to clean up that mess of callbacks, it seems my deferred never gets called. I'm familiar with the concepts of deferred from Python's Twisted, so I think conceptually everything should work - but it doesn't.
This is the shortest example I could come up with, the slow WebSockets server is simulated with a setTimeout function.
<!doctype html>
<html ng-app="beta">
<head>
<title>Beta</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
<script>
var beta = angular.module('beta', []);
var BetaCtrl = function ($scope, betaServ) {
$scope.button = function () {
serv_result = betaServ.slow();
console.log(serv_result);
serv_result.then(function (result) {
console.log('callback finished');
});
}
}
beta.service('betaServ', function($q) {
this.slow = function () {
d = $q.defer()
setTimeout(function () {
console.log('before resolve');
d.resolve();
console.log('after resolve');
}, 2000);
return d.promise;
}
});
</script>
</head>
<body>
<div ng-controller="BetaCtrl">
<button ng-click="button()">Run</button>
</div>
</body>
</html>
The could should run as following:
Any ideas? Thanks.
You need to call your callback with $apply since it's called outside of Angular. Since this is a service, you'll need to include $rootScope in your service:
beta.service('betaServ', function($q, $rootScope) {
this.slow = function () {
d = $q.defer()
setTimeout(function () {
console.log('before resolve');
$rootScope.$apply(d.resolve);
console.log('after resolve');
}, 2000);
return d.promise;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With