Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question
2  
If you can use $q, why can't you use $http ? –  finishingmove Jun 24 '13 at 2:13
    
you should refactor your code to use $http if you can use $q –  Ajay Beniwal Jun 24 '13 at 5:24
    
I would choose 1st solution. –  Ye Liu Jun 24 '13 at 5:32
    
Project is too big and too old. We will rewrite API module soon :) The question is about usage of AJAX requests without $http :) I suppose that lots projects have own implementation of json-rpc module or something like that and can't replace it for whole project easily :) Part of code is written without AngularJS :) –  InviS Jun 24 '13 at 5:40
    
You are not even using a $timeout in example 1 ...? If 1. works, it's the better choice, as defer.resolve naturally starts a digest cycle, which is imo always preferable to manually starting it. –  Narretz Jun 24 '13 at 8:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.