I was always under the impression that if you were using $q in a service, and returning the promise, you did not need to wrap in scope.$apply -- but then again, the docs for $q show the async setTimeout is wrapped in scope.$apply =>
http://docs.angularjs.org/api/ng.$q
That begs a second question, the example there just assumes "scope is injected somehow"
- // for the purpose of this example let's assume that variables `$q` and `scope` are
- // available in the current lexical scope (they could have been injected or passed in).
In a service, there is no scope, per se. You can inject the $rootScope. So, here's my conundrum / question. Let's say I have a 3rd party async api that looks like this:
foo.doSomething( function success (data) { /* do something with data */ }, function error (err) { /* do something with error */ } );
I want to wrap this in a service, so which way is correct?
app.factory('myservice', ['$q', function ($q) {
return {
get: function () {
var deferred = $q.defer();
foo.doSomething(function (data) {
promise.resolve(data);
}, function (err) {
promise.reject(err);
});
return deferred.promise;
}
};
}]);
OR
app.factory('myservice', ['$q', '$rootScope', function ($q, $rootScope) {
return {
get: function () {
var deferred = $q.defer();
$rootScope.$apply(function () {
foo.doSomething(function (data) {
promise.resolve(data);
}, function (err) {
promise.reject(err);
});
});
return deferred.promise;
}
};
}]);