Being relatively new to angularjs, I am seeking advice on the best practice for tackling a specific issue. In my controller1
, there is a validation function used for registration form validation that is invoked from my uniqueField
directive as an attribute:
$scope.validation=function(param){
$scope.loading[param.field]=true;
var currentPath=$location.path(); //current route
//function for ajax web call
var webCall = $http({
method: 'POST',
url: currentPath+'/validation',
async : true,
headers: {
'Content-Type': 'application/json'
},
timeout:10000,
data: param});
webCall.then(handleSuccess,handleError); //server call
function handleSuccess(response) { //successful web call handler
$scope.loaded[param.field]={};
$scope.loading[param.field]=false;
if(response.data.status===1) {
$scope.loaded[param.field]["available"]=true;
$scope.loaded[param.field]["error"]=false;
$scope.loaded[param.field]["message"]=response.data.message;
}
else if(response.data.status===0){
$scope.loaded[param.field]["available"]=false;
$scope.loaded[param.field]["error"]=false;
$scope.loaded[param.field]["message"]=response.data.message;
}
}
function handleError(response){
$scope.loaded[param.field]={};
$scope.loading[param.field]=false;
$scope.loaded[param.field]["error"]=true;
$scope.loaded[param.field]["Message"]="Cannot fetch data from server";
};
}
}
With a need for similar functionality in another controller, what would be the optimal approach to avoid duplicating the function definition?