I'm facing an issue in my AngularJS function where the $http request is being fired before my first function is completed.
Here's a sample of how my code looks:
$scope.function = function(){
$scope.functionOne(); // This function initializes all the scope variables needed for the API call
$scope.functionTwo(); // This function sends a POST request to the API using $http.post
}
Unfortunately, all the variables are empty strings by the time they reach the backend because $http fires the request prematurely.
UPDATE
$scope.functionOne = function(){
var geocoder = new google.maps.Geocoder();
if(geocoder){
// console.log("dean")
// console.log($scope.dealership.address);
// console.log($scope.dealership.suburb)
geocoder.geocode({
'address': $scope.dealership.address + ', ' + $scope.dealership.suburb || "1/53 Township Drive, West Burleigh"
}, function(result, status){
// console.log("armada");
// console.log(status);
if(status == google.maps.GeocoderStatus.OK){
console.log(result);
var center_lat = result[0].geometry.location.lat();
var center_lng = result[0].geometry.location.lng();
var lat = result[0].geometry.location.lat();
var lng = result[0].geometry.location.lng();
$scope.$apply();
}
$scope.map.center.latitude = center_lat;
$scope.map.center.longitude = center_lng;
$scope.map.markers.pop();
$scope.map.markers.push({
latitude: lat,
longitude: lng
});
$scope.dealership.latitude = lat;
$scope.dealership.longitude = lng;
$scope.$apply();
});
}};
$scope.functionTwo = function(){
$scope.loadingData = true;
// The code below is a factory on a scope variable
$scope.dealership.create().then(function(response){
});
}