Assume we have some service that fetch data from server. It's async and is not using AngularJS $http service.
When we deal with async stuff in Angular - we use $q
promises. But there is one problem: promises are resolved only after $digest
.
There are 2 possible ways to fix it:
1) $timeout
var defer = $q.defer();
$.getJSON('http://example.com/my.json')
.success(function (data) {
$timeout(function () {
defer.resolve(data);
});
});
return defer.promise;
2) $rootScope.$apply()
var defer = $q.defer();
$.getJSON('http://example.com/my.json')
.success(function (data) {
defer.resolve(data);
});
if (!$rootScope.$$phase) $rootScope.$apply();
In AngularJS $http
service second variant is used.
What the difference between both is and what is proper way to do such stuff?
You are able to try both methods in action: http://jsbin.com/otakaw/3/edit