You want to create your own promise with$q . Here's how I did something similar in a recent project:
app.service('allData', ['$http','$q',function($http,$q) {
return {
getJson: function() {
return $q(function(resolve, reject) {
$http.get('/path/to/data.json', {cache:true})
.success(function(data) {
if (angular.isArray(data)) {
resolve(data);
} else {
reject("Invalid JSON returned");
console.log(data);
};
})
.error(function(data) {
reject("Invalid data returned");
console.log(data);
});
});
}
};
}]);
And in my controller:
allData.getJson().then(function(json) {
}, function(reason) {
alert('Sorry, unable to retrieve data from the server.')
console.error(reason);
});
source
share