The previous answer is good in terms of reusing it as a service. But it looks like you really want to ignore the logic of repetition. This is how I do it.
app.service('SessionService', ['$http', '$q', function($http, $q){ var _this = this; var _maxRetryCount = 5; //Just have a maxRetryCount this.StartSession = function (code, retries){ //if you dont pass retry take the maxretryCount retries = angular.isUndefined(retries) ? _maxRetryCount : retries; return $http.get('ajax.php?a=StartSession&ref=' + code) .then(function(result) { //process and return the result return result.data; }, function (errorResponse) { //If retries left decrement count and make the call again. if(retries) { return _this.StartSession(code, --retries); //here we are returning the promise } //All tried done Now Fail or return some data return $q.reject('oops failed after retries'); }); } }]);
And just add a SessionService anywhere in your controller: -
SessionService.StartSession(code).then(function(result){
Plnkr
source share