I have custom module that get data from api. it's async, so i use defer for it.
angular.module('module', []).factory('api', function($q){
var $scope;
return {
setScope: function(scope){ $scope = scope; },
getPic:function(){
var def = $q.defer();
$.ajax({
url: 'https://graph.facebook.com/shaverm/picture?redirect=false',
dataType: 'jsonp',
success: function(r){
def.resolve(r.data.url);
$scope.$apply();
},
});
return def.promise
}
}
});
It works fine, but i'm worrying about using scope.$apply in the module.
Here is example http://jsfiddle.net/mfbFs/
Can it be improved?
Why are you using jQuery's ajax, when Angular comes with it and has a built-in promise?
angular.module('module', []).factory('api', function($http){
return {
getPic: function(){
return $http.jsonp('https://graph.facebook.com/shaverm/picture?redirect=false&callback=JSONP_CALLBACK');
}
};
});
Much simpler! And no need to worry about the digest - your controller will already ensure that happens when it should.
You don't need to set the $scope before calling the API, just inject the $rootScope on the service and call $apply() (or $digest()) on that scope, like this:
angular.module('module', []).factory('api', function($q, $rootScope){
return {
getPic:function(){
var def = $q.defer();
$.ajax({
url: 'https://graph.facebook.com/shaverm/picture?redirect=false',
dataType: 'jsonp',
success: function(r){
def.resolve(r.data.url);
$rootScope.$apply();
},
});
return def.promise
}
}
});
function demoCtrl ($scope, api){
$scope.url = api.getPic();
}