I’m new to AngularJS, so this might actually point to some core concept that I don’t yet understand completely. I’m trying to treat “remote data” like local data using $q & promise objects. Till the time the remote data is not fetched, the promise object doesn’t resolve, but as soon as it resolves, I want all the dependent data-bindings in the view to get updated. However, the following approach is resulting in an infinite loop where remote_total is being called repeatedly, even through the previous call to remote_total resulted in a resolved promise object.
Here’s what my view looks like
<div ng-controller="MyController">
{{ remote_total() }}
</div>
Here’s the relevant snippet from the controller:
function MyController($scope, $q, $http) {
$scope.remote_total = function() {
var def = $q.defer();
$http.get('/my/remote/service.json').success(function(data) {
def.resolve(data);
});
return def.promise;
}
}
Firstly, it would be great if anyone could explain to me why exactly is this getting into an infinite loop. Secondly, what’s the best way to achieve what I’m trying to do?
NOTE: See UPDATE below for Angular 1.2+
Actually interesting thing with AngularJS’s promises (that
$qprovides) that they’re recognized by AngularJS. And another that they are chainable!So in your code you can just do
and at view just
<div>{{remote total}}</div>(note: not function, just value).And AngularJS will automatically recognize it’s promise, resolve $http.get promise, then chain into your function and put resulting value into template.
That’s all 🙂
UPDATE: Automatic de-wrapping of promises are disabled by default in AngularJS 1.2 and would be completely removed in 1.3.
Code that will work: